在XmlArrayItemAttribute类中使用IsNullable =true 。举个例子。
[XmlRoot("Root")]
public class Root
{
[XmlArrayItem("Element", IsNullable = true)]
public string[] Elements { get; set; }
}
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())));
}
输出是(为清楚起见添加了换行符):
<?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>
并且具有复杂类型(也在 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
使用上面相同的代码会产生:
<?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>
还要记住,类型必须是引用类型(例如,不是结构)才能写出xsi:nil=true
。