【问题标题】:child node is not getting serialized correctly子节点未正确序列化
【发布时间】:2019-08-04 17:54:23
【问题描述】:

在尝试让我的模型的 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 序列化程序似乎忽略了子类元素。

【问题讨论】:

  • 查找 XmlArrayAttribute 和 XmlArrayItemAttribute

标签: c# xml xml-parsing


【解决方案1】:

好吧,愚蠢的错误,需要将“Items”更改为 XmlArrayItem 而不是 Element

[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; }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2018-12-07
    • 2011-12-20
    相关资源
    最近更新 更多