使用不同元素将XML反序列化为分隔列表

时间:2017-10-06 16:14:50

标签: c# .net xml deserialization

请你帮我解决当前xml的反序列化问题:

<ObjectList>
  <Item Attr1="1"/>
  <Item Attr1="2"/>
  <DifferentItem Attr2="5"/>    
</ObjectList>

我想在结构中反序列化它

public class ObjectList
{
    public List<Item> Items { get; set; }
    public List<DifferentItem> DifferentItems { get; set; }
}

public class Item
{
    public string Attr1 { get; set; }
}

public class DifferentItem
{
    public string Attr2 { get; set; }
}

我尝试了属性,但未成功

[XmlArray("ObjectList")]
[XmlArrayItem("Item", typeof(Item))]

我该如何解决这个问题? 感谢)

2 个答案:

答案 0 :(得分:2)

添加属性:

public class ObjectList
{
    [XmlElement("Item")]
    public List<Item> Items { get; set; }
    [XmlElement("DifferentItem")]
    public List<DifferentItem> DifferentItems { get; set; }
}

答案 1 :(得分:0)

您需要使用XML属性来帮助将XML映射到类和属性。这是我用XML编写的控制台应用程序,它被解析好了。请注意我是如何使用XmlRoot和XmlElement属性来映射它的。

public class Program
{
    public static void Main()
    {
        var serializer = new XmlSerializer(typeof(ObjectList));
        var xml = "<ObjectList><Item Attr1=\"1\" /><Item Attr1=\"2\" /><DifferentItem Attr2=\"5\" /></ObjectList>";

        using (var reader = new StringReader(xml))
        {
            var schedule = (ObjectList)serializer.Deserialize(reader);
        }
    }

    [XmlRoot("ObjectList")]
    public class ObjectList
    {
        [XmlElement("Item")]
        public List<Item> Items { get; set; }

        [XmlElement("DifferentItem")]
        public List<DifferentItem> DifferentItems { get; set; }
    }

    public class Item
    {
        [XmlAttribute("Attr1")]
        public string Attr1 { get; set; }
    }


    public class DifferentItem
    {
        [XmlAttribute("Attr2")]
        public string Attr2 { get; set; }
    }
}