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

时间:2015-08-05 06:06:33

标签: c# xml xml-parsing

def LCG(seed, n, a=1664525, c=1013904223, m=2**32): numbers = [] for i in xrange(n): seed = (a * seed + c) % m numbers.append(seed) return numbers print LCG(3, 5) 序列化为object时,如果对象属性值为null XML,则不添加该元素。如何使用空值在XML中添加该元素?

例如:

Serializer

Serializer Class

[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

0 个答案:

没有答案