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

时间:2011-10-28 20:34:40

标签: 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" />

表达相应类结构的简洁方法是什么?

我非常确定以下内容:

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();
        }
    }
}

以及:

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();
        }
    }
}

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

编辑:我最终使用this answer中的信息。

3 个答案:

答案 0 :(得分:6)

尝试将IsNullable = true添加到XmlArrayItem属性。

答案 1 :(得分:4)

看起来您可以使用另一个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;
}

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

答案 2 :(得分:0)

XxySpecifed属性的附加内容,还有一个ShouldSerialize前缀的方法

[XmlElement]
public List<string> OptionalXyz {get; set;}

public bool ShouldSerializeOptionaXyz() {
    return OptionalXyz != null && OptionalXyz.Count > 0 ;
}