简体   繁体   English

序列化列表 <knowntype> 到特定的xml格式

[英]serializing a List<knowntype> to a specific xml format

I have this list property in a class and I need to decorate it with the correct xml attributes to get it in the form: 我在一个类中有此列表属性,我需要用正确的xml属性对其进行修饰以使其具有以下形式:

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

when I serialize the object. 当我序列化对象时。 Here is the declaration of the list property within the class: 这是该类中list属性的声明:

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

Currently what I get is this: 目前我得到的是:

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

Its clear to me that the "Documents" node I want should be declared something other than an XmlArrayItemAttribute. 对我来说很清楚,我想要的“文档”节点应该声明为XmlArrayItemAttribute以外的其他值。 The name of the list can not change. 列表名称不能更改。 Help me Obi Wan Kenobi, you're my only hope. 帮我Obi Wan Kenobi,您是我唯一的希望。

You did not specify how the 'DocumentType' looks like but can define it as follow: 您没有指定“ 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;
        }
    }
}

The Xml after serialization: 序列化后的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM