gpt4 book ai didi

c# - 反序列化复杂对象中的xml

转载 作者:行者123 更新时间:2023-11-30 22:30:05 25 4
gpt4 key购买 nike

我不明白为什么对象为空:

        WebClient browse = new WebClient();
StreamReader res = new StreamReader(browse.OpenRead("http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=cher&track=believe"));
string result = res.ReadToEnd();

XmlDocument xmltrackinfo = new XmlDocument();
xmltrackinfo.InnerXml = result;



XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "lfm";
xRoot.IsNullable = true;

XmlSerializer xs = new XmlSerializer(typeof(fm), xRoot);

fm rez = (fm) xs.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(result)));

对象模型:

[Serializable()]
[XmlRoot(ElementName = "lfm", IsNullable = true)]
public class fm
{
[XmlElement("lfm")]
public Track lfm { get; set; }
}

[Serializable()]
[XmlRoot(ElementName = "artist", IsNullable = true)]
public class artist
{
public string name { get; set; }
public string mbid { get; set; }
public string url { get; set; }
}

[Serializable()]
[XmlRoot(ElementName = "album", IsNullable = true)]
public class album
{
public string artist { get; set; }
public string title { get; set; }
public string mbid { get; set; }
public string url { get; set; }
public List<string> image { get; set; }
}

[Serializable()]
[XmlRoot(ElementName = "tag", IsNullable = true)]
public class tag
{
public string name { get; set; }
public string url { get; set; }

}

[Serializable()]
[XmlRoot(ElementName = "wiki", IsNullable = true)]
public class wiki
{
public string summary { get; set; }
public string content { get; set; }
}

[Serializable()]
[XmlRoot(ElementName = "track", IsNullable = true)]
public class Track
{
public string id { get; set; }
public string name { get; set; }
public string mbid { get; set; }
public string url { get; set; }
public string duration { get; set; }
public string streamable { get; set; }
public string listeners { get; set; }
public string playcount { get; set; }
public artist artist { get; set; }
public album album { get; set; }
public List<tag> toptags { get; set; }
public wiki wiki { get; set; }

}

和 XML:

http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=cher&track=believe

那我该怎么办呢?

最佳答案

尝试将您的 fm 类重命名为 lfm

public class lfm
{
public Track track { get; set; }
}

然后你也可以去掉 xRoot 变量:

XmlSerializer xs = new XmlSerializer(typeof(lfm));
lfm rez = (lfm) xs.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(result)));

您也不需要 [Serializable] 属性。这用于二进制序列化并被 XmlSerializer 类完全忽略。

关于c# - 反序列化复杂对象中的xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9870909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com