首页 新闻 会员 周边 捐助

解析XML内容失败,求解答!

0
悬赏园豆:10 [已解决问题] 解决于 2013-10-31 07:50

如下代码,简单例子,为什么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; }
        }
    }
xml
醉低调的主页 醉低调 | 初学一级 | 园豆:128
提问于:2013-10-30 18:43
< >
分享
最佳答案
0

把 

[XmlElement("items")]

public List<B> list { get; set; }

改成

[XmlArray(ElementName = "items")]
[XmlArrayItem(ElementName = "model")]
public List<B> list { get; set; }

收获园豆:10
Yu | 专家六级 |园豆:12990 | 2013-10-30 22:27
其他回答(1)
0

当序列化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; }
        }

 

贪心狸猫 | 园豆:872 (小虾三级) | 2013-10-30 19:53

貌似不行啊。

支持(0) 反对(0) 醉低调 | 园豆:128 (初学一级) | 2013-10-30 20:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册