如何为可选的XML元素装饰/定义类成员以与XmlSerializer一起使用?

Joh*_*ohn 5 c# xmlserializer

我有以下XML结构.该theElement元素可以包含theOptionalList元素,或不:

<theElement attrOne="valueOne" attrTwo="valueTwo">
    <theOptionalList>
        <theListItem attrA="valueA" />
        <theListItem attrA="anotherValue" />
        <theListItem attrA="stillAnother" />
    </theOptionalList>
</theElement>
<theElement attrOne="anotherOne" attrTwo="anotherTwo" />
Run Code Online (Sandbox Code Playgroud)

什么是表达相应类结构的干净方式?

我很确定以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace MyNamespace
{
    public class TheOptionalList
    {
        [XmlAttributeAttribute("attrOne")]
        public string AttrOne { get; set; }

        [XmlAttributeAttribute("attrTwo")]
        public string AttrTwo { get; set; }

        [XmlArrayItem("theListItem", typeof(TheListItem))]
        public TheListItem[] theListItems{ get; set; }

        public override string ToString()
        {
            StringBuilder outText = new StringBuilder();

            outText.Append("attrOne = " + AttrOne + " attrTwo = " + AttrTwo + "\r\n");

            foreach (TheListItem li in theListItems)
            {
                outText.Append(li.ToString());
            }

            return outText.ToString();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以及:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace MyNamespace
{
    public class TheListItem
    {
        [XmlAttributeAttribute("attrA")]
        public string AttrA { get; set; }

        public override string ToString()
        {
            StringBuilder outText = new StringBuilder();

            outText.Append("  attrA = " + AttrA + "\r\n");                
            return outText.ToString();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是theElement呢?我是否将theOptionalList元素作为数组类型来读取它在文件中找到的内容(无论是什么,还是一个),然后检查代码是否存在?或者我可以提供另一个装饰器吗?或者它只是工作?

编辑: 我最终使用了这个答案的信息.

Jam*_*son 6

尝试添加IsNullable = trueXmlArrayItem属性.


K2s*_*2so 5

看起来您可以使用另一个 bool 来指定是否包含元素。

另一种选择是使用特殊模式创建 XmlSerializer 识别的布尔字段,并将 XmlIgnoreAttribute 应用于该字段。该模式以propertyNameSpecified 的形式创建。例如,如果有一个名为“MyFirstName”的字段,您还将创建一个名为“MyFirstNameSpecified”的字段,以指示 XmlSerializer 是否生成名为“MyFirstName”的 XML 元素。这在以下示例中显示。

public class OptionalOrder
{
    // This field should not be serialized 
    // if it is uninitialized.
    public string FirstOrder;

    // Use the XmlIgnoreAttribute to ignore the 
    // special field named "FirstOrderSpecified".
    [System.Xml.Serialization.XmlIgnoreAttribute]
    public bool FirstOrderSpecified;
}
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx