【问题标题】:serializing a List<knowntype> to a specific xml format将 List<knowntype> 序列化为特定的 xml 格式
【发布时间】:2015-02-04 00:15:02
【问题描述】:

我在一个类中有这个列表属性,我需要用正确的 xml 属性来装饰它以获取它的形式:

<Attachments>
    <Documents>
        <Document>
            the DocumentType nodes...
        </Document>
        <Document>
            the DocumentType nodes...
        </Document>
    </Documents>
</Attachments>

当我序列化对象时。下面是类中 list 属性的声明:

[XmlArrayItem("Documents", IsNullable = false)]
[XmlArrayItem("Document", IsNullable = false, NestingLevel = 1)]
public List<DocumentType> Attachments
{
    get
    {
        return this._attachments;
    }
    set
    {
        this._attachments = value;
    }
}

目前我得到的是这样的:

<Attachments>
    <Documents>
        the DocumentType nodes...
    </Documents>
    <Documents>
        the DocumentType nodes...
    </Documents>
</Attachments>

我很清楚,我想要的“文档”节点应该声明为 XmlArrayItemAttribute 以外的其他内容。列表的名称不能更改。帮助我 Obi Wan Kenobi,你是我唯一的希望。

【问题讨论】:

  • 试试改成[XmlArray("Documents")] [XmlArrayItem("Document")]

标签: c# xml


【解决方案1】:

您没有指定“DocumentType”的外观,但可以将其定义如下:

public class DocumentType
    {
        [XmlElement("Document")]
        public string Name {get; set;}
    }


public class Test
{
    private List<DocumentType> _attachments = new List<DocumentType>();

    [XmlArrayItem("Documents", IsNullable = false)]
    public List<DocumentType> Attachments
    {
        get
        {
            return this._attachments;
        }
        set
        {
            this._attachments = value;
        }
    }
}

序列化后的xml:

<?xml version="1.0"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Attachments>
    <Documents>
      <Document>A Node</Document>
      <Document>B Node</Document>
    </Documents>
  </Attachments>
</Test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多