在C#中,可以将空字符串序列化为nil值。让我们像这样来看这个对象:
var myBook = new Book(){ Author = "John S.", ISBN = null };我想要:
<Book>
<Author>John S.</Author>
<ISBN nil="true"/>
</Book>有没有可能用像ExtendedXmlSerializer或YAXLib这样的第三方xml序列化程序来实现这样的结果?
致以问候。
发布于 2018-01-27 21:04:50
您可以尝试这样做:
var myBook = new Book() { Author = "John S.", ISBN = null };
XmlSerializer xs = new XmlSerializer(typeof(Book));
StringWriter sw = new StringWriter();
xs.Serialize(sw, myBook);
Console.WriteLine(sw.ToString() );此外,您还需要添加一个属性:
public class Book
{
public string Author { get; set; }
[System.Xml.Serialization.XmlElement(IsNullable = true)]
public string ISBN { get; set; }
}结果:
<?xml version="1.0" encoding="utf-16"?>
<Book xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Author>John S.</Author>
<ISBN xsi:nil="true" />
</Book>https://stackoverflow.com/questions/48476052
复制相似问题