提问人: 提问时间:8/5/2015 更新时间:8/5/2015 访问量:2591
XmlSerializer - 添加为 Object 中 Null 属性的空元素
XmlSerializer - Add as Empty Element for Null property in Object
问:
序列化 to 时,当对象属性值为 null 时,不会添加该元素。如何在XML中添加该元素的空值?object
XML
Serializer
ggø
[XmlRoot(ElementName ="Employee")]
public class Employee
{
[XmlElement(ElementName = "EmployeeId", IsNullable = false)]
public int EmployeeId {get;set;}
[XmlElement(ElementName = "EmployeeName", IsNullable = false)]
public string EmployeeName {get;set;}
}
序列化程序类
public static class GenericXmlSerializer
{
public static string SerializeObject<T>(this T toSerialize)
{
var xmlSerializer = new SystemXml.XmlSerializer(toSerialize.GetType());
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
}
解析
var emp = new Employee();
emp.SerializeObject();
实际输出:
<?xml version="1.0" encoding="utf-16"?>
<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
预期输出:
<?xml version="1.0" encoding="utf-16"?>
<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<Employee>
<EmployeeId></EmployeeId>
<EmployeeName></EmployeeName>
</Employee>
有什么想法吗?
评论后编辑:
更改时,输出如下所示,这与预期不符。IsNullable=true
<?xml version="1.0" encoding="utf-16"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EmployeeId xsi:nil="true" />
</Employee>
答: 暂无答案
评论
DefaultValue
DefaultValue
Reset