将List <knowntype>序列化为特定的xml格式</knowntype>

时间:2015-02-04 00:15:02

标签: c# xml

我在类中有这个list属性,我需要使用正确的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>

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

1 个答案:

答案 0 :(得分:0)

您没有指定'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