如下代码,简单例子,为什么list为1,而且内容都为空? 度娘也没什么好办法呀。
public class Program { public static void Main(string[] args) { string x = @" <xml> <id>123123</id> <items> <model> <name>1</name> <age>2</age> </model> <model> <name>3</name> <age>4</age> </model> </items> </xml> "; System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(A)); var mmi = xs.Deserialize(new XmlTextReader(new StringReader(x))) as A; var list = mmi.list.Count; } [XmlRoot(ElementName = "xml")] public class A { [XmlElement("id")] public int id { get; set; } [XmlElement("items")] public List<B> list { get; set; } } [XmlRoot(ElementName = "model")] public class B { [XmlElement("name")] public string name { get; set; } [XmlElement("age")] public int age { get; set; } } }
把
[XmlElement("items")]
public List<B> list { get; set; }
改成
[XmlArray(ElementName = "items")]
[XmlArrayItem(ElementName = "model")]
public List<B> list { get; set; }
当序列化A.list的时候,XmlElement指的是B.可以改成
[XmlRoot(ElementName = "xml")]
public class A
{
[XmlElement("id")]
public int id { get; set; }
//[XmlElement("model")]
[XmlArrayItem("model")]
public List<B> items { get; set; }
}
[XmlRoot(ElementName = "model")]
public class B
{
[XmlElement("name")]
public string name { get; set; }
[XmlElement("age")]
public int age { get; set; }
}
貌似不行啊。