尝试使模型的xml序列化正常工作时遇到问题。
这是我的模特:
[XmlRoot(ElementName = "Invoice", Namespace = "", IsNullable = false)]
public class Invoice
{
[XmlElement(ElementName = "Items")]
public virtual List<Item> Items{ get; set; }
}
[XmlRoot(ElementName = "Item")]
public class Item
{
[XmlAttribute(AttributeName = "Line")]
public virtual int Line { get; set; }
[XmlAttribute(AttributeName = "MatNum")]
public virtual string MatNum { get; set; }
}
这将导致以下XML错误:
<?xml version="1.0" encoding="utf-16"?>
<Invoice>
<Items Line="1" MatNum="Beer">
<Items Line="2" MatNum="Cola">
</Invoice>
结果应如下所示:
<?xml version="1.0" encoding="utf-16"?>
<Invoice>
<Items>
<Item Line="1" MatNum="Beer">
<Item Line="2" MatNum="Cola">
</Items>
</Invoice>
我在做什么错?看起来XML序列化程序正在忽略子类元素。
答案 0 :(得分:1)
好傻的错误,需要更改为XmlArrayItem而不是“ Items”的元素
[XmlRoot(ElementName = "Invoice", Namespace = "", IsNullable = false)]
public class Invoice
{
[XmlArrayItem(ElementName = "Item")]
public virtual List<Item> Items { get; set; }
}
[XmlRoot(ElementName = "Item")]
public class Item
{
[XmlAttribute(AttributeName = "Line")]
public virtual int Line { get; set; }
[XmlAttribute(AttributeName = "MatNum")]
public virtual string MatNum { get; set; }
}