[英]Deserialize XML with different elements to separated lists
Could you please help me with deserialization of current xml:你能帮我反序列化当前的xml吗:
<ObjectList>
<Item Attr1="1"/>
<Item Attr1="2"/>
<DifferentItem Attr2="5"/>
</ObjectList>
I want to deserialize it in structure like this我想在这样的结构中反序列化它
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; }
}
I tried attributes, but unsuccessfully我尝试了属性,但没有成功
[XmlArray("ObjectList")]
[XmlArrayItem("Item", typeof(Item))]
How can I solve this?我该如何解决这个问题? Thanks)谢谢)
Add attributes:添加属性:
public class ObjectList
{
[XmlElement("Item")]
public List<Item> Items { get; set; }
[XmlElement("DifferentItem")]
public List<DifferentItem> DifferentItems { get; set; }
}
You need to use XML attributes to help map XML to classes and properties.您需要使用 XML 属性来帮助将 XML 映射到类和属性。 Here's a console app I wrote with your XML, and it gets parsed OK.这是我用你的 XML 编写的控制台应用程序,它被解析为 OK。 Notice how I used the XmlRoot and XmlElement attributes to map it.请注意我如何使用 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; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.