Сериализация XML Unity3D
Как получить данные из XML, получаемого с сервера яндекс диска?
string text = www.downloadHandler.text;
Текст имеет вот такой вид: <?xml version="1.0" encoding="UTF-8"?><d:multistatus xmlns:d="DAV:"><d:response><d:href>/folder/image.jpg</d:href><d:propstat><d:prop><public_url xmlns="urn:yandex:disk:meta">https://yadi.sk/i/bYlIeaB5x</public_url></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>
Нужно получить отсюда ссылку, как это сделать?
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
using System.Xml.Serialization;
Вот такая модель данных
public class PublicUrl
{
[XmlText]
public string Text { get; set; }
}
public class Prop
{
[XmlElement(ElementName = "public_url", Namespace = "urn:yandex:disk:meta")]
public PublicUrl PublicUrl { get; set; }
}
public class Propstat
{
[XmlElement(ElementName = "prop")]
public Prop Prop { get; set; }
[XmlElement(ElementName = "status")]
public string Status { get; set; }
}
public class Response
{
[XmlElement(ElementName = "href")]
public string Href { get; set; }
[XmlElement(ElementName = "propstat")]
public Propstat Propstat { get; set; }
}
[XmlRoot(ElementName = "multistatus", Namespace = "DAV:")]
public class Multistatus
{
[XmlElement(ElementName = "response")]
public Response Response { get; set; }
}
И вот так десереализовать
static void Main(string[] args)
{
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><d:multistatus xmlns:d=\"DAV:\"><d:response><d:href>/folder/image.jpg</d:href><d:propstat><d:prop><public_url xmlns=\"urn:yandex:disk:meta\">https://yadi.sk/i/bYlIeaB5x</public_url></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>";
using StringReader reader = new StringReader(xml);
XmlSerializer serializer = new XmlSerializer(typeof(Multistatus));
Multistatus data = (Multistatus)serializer.Deserialize(reader); // сюда любой Stream или TextReader подойдет
Console.WriteLine(data.Response.Href);
Console.WriteLine(data.Response.Propstat.Prop.PublicUrl.Text);
Console.WriteLine(data.Response.Propstat.Status);
}
Вывод в консоль
/folder/image.jpg
https://yadi.sk/i/bYlIeaB5x
HTTP/1.1 200 OK