XmlSerializer - 添加为 Object 中 Null 属性的空元素

XmlSerializer - Add as Empty Element for Null property in Object

提问人: 提问时间:8/5/2015 更新时间:8/5/2015 访问量:2591

问:

序列化 to 时,当对象属性值为 null 时,不会添加该元素。如何在XML中添加该元素的空值?objectXMLSerializer

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>
C# XML 解析

评论

0赞 Joseph 8/5/2015
[XmlElement(ElementName = “EmployeeId”, IsNullable = true)] 你可以像这样尝试吗.please set IsNullable = true 并尝试。
0赞 8/5/2015
@Joseph,请看我的编辑
0赞 Joseph 8/5/2015
请查看此 msdn.microsoft.com/en-us/library/53b8022e(v=vs.110).aspx
0赞 8/5/2015
@Joseph,谢谢! 可能会对我有所帮助,但它没有按预期工作,我还需要标记每个属性,并且需要有方法,当有很多属性时,这种方法很复杂。有什么最好和有效的方法来实现它吗?DefaultValueDefaultValueReset

答: 暂无答案