【发布时间】:2014-11-11 11:18:40
【问题描述】:
我正在尝试解析一个 xml 数组,它在一个奇怪的地方有一个属性。
这是我的(在 stackowerflow 上的某处找到)解析器代码:
public static string Serialize (object objectToSerialize)
{
MemoryStream mem = new MemoryStream ();
XmlSerializer ser = new XmlSerializer (objectToSerialize.GetType ());
ser.Serialize (mem, objectToSerialize);
UTF8Encoding utf = new UTF8Encoding ();
return utf.GetString (mem.ToArray ());
}
public static T Deserialize<T> (string xmlString)
{
byte[] bytes = Encoding.UTF8.GetBytes (xmlString);
MemoryStream mem = new MemoryStream (bytes);
XmlSerializer ser = new XmlSerializer (typeof(T));
return (T)ser.Deserialize (mem);
}
这适用于所有情况(我需要),除了这里:
<hr>
<type n="easy">
<scores>
<country name="USA">
<score nickname="steve" rank="1">1982</score>
<score nickname="bill" rank="2">1978</score>
...
这是我的模板类:
public class CountryList
{
public CountryList ()
{
}
[XmlArray("country")]
[XmlArrayItem("score")]
public ScoreAndRank[]
country;
[XmlAttribute("name")]
public string
name;
}
}
分数数组已正确解析,但“名称”始终为空。 我什至可以得到 n 的值(如 [XmlAttribute("n")])。 任何提示如何解决这个问题?
编辑:基于 Svein Fidjestøl 链接的解决方案
[XmlType("country")]
public class ScoreContainer
{
public ScoreContainer ()
{
}
[XmlElement("score")]
public ScoreAndRank[] country;
[XmlAttribute("name")]
public string name;
}
像魅力一样工作。
【问题讨论】:
标签: c# xml xml-parsing