[XmlText]序列化可以为空吗?

lad*_*dge 7 .net xmlserializer

我有一个包含我想用XmlSerializer序列化的数组的类:

[XmlArray("properties")]
[XmlArrayItem("property", IsNullable = true)]
public List<Property> Properties { get; set; }
Run Code Online (Sandbox Code Playgroud)

Property是一个包含属性的类,有些XmlText:

[XmlAttribute("name")]
public string Name { get; set; }

[XmlText]
public string Value { get; set; }
Run Code Online (Sandbox Code Playgroud)

问题是,当Value为null时,它序列化为空字符串:

<property name="foo" />
Run Code Online (Sandbox Code Playgroud)

而不是null.我正在寻找要完全省略的值,或者看起来像这样:

<property name="foo" xsi:nil="true" />
Run Code Online (Sandbox Code Playgroud)

是否可以根据其XmlText值清空列表中的元素?我真的想避免自定义序列化,但在这种情况下,或许其他一些序列化框架会更好?

akt*_*ton 2

在XmlArrayItemAttribute类中使用IsNullable =true 。举个例子。

[XmlRoot("Root")]
public class Root
{
    [XmlArrayItem("Element", IsNullable = true)]
    public string[] Elements { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Visual Studion 2012 和 .Net 4.5 中的一些示例代码:

using System.Xml.Serialization;

...

// Test object
Root root;
root = new Root();
root.Elements = new string[] { null, "abc" };

using(MemoryStream stream = new MemoryStream())
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Root));
    xmlSerializer.Serialize(stream, root);

    Console.WriteLine(new string(Encoding.UTF8.GetChars(stream.GetBuffer())));
}
Run Code Online (Sandbox Code Playgroud)

输出为(为了清晰起见添加了换行符):

<?xml version="1.0"?>
<Root 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Element>
    <string xsi:nil="true" />
    <string>abc</string>
  </Element>
</Root>
Run Code Online (Sandbox Code Playgroud)

对于复杂类型(也在 Visual Studio 2012 上的 .Net 4.5 中):

    public class MyProperty
    {
        public string Foo { get; set; }
    }

    [XmlRoot("Root")]
    public class Root
    {
        [XmlArrayItem("Element", IsNullable = true)]
        public MyProperty[] Elements { get; set; }
    }

    ,,,

    Root root;
    root = new Root();
    root.Elements = new MyProperty[] { null, new MyProperty{ Foo = "bar" } };

    // Other code is as above
Run Code Online (Sandbox Code Playgroud)

使用上面相同的代码会产生:

<?xml version="1.0"?>
<Root 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Elements>
    <Element xsi:nil="true" />
    <Element>
      <Foo>bar</Foo>
    </Element>
  </Elements>
</Root>
Run Code Online (Sandbox Code Playgroud)

还要记住,要写出的类型必须是引用类型(例如,不是结构体)xsi:nil=true