XmlSerializer - Add as empty element for Null property in object

Serializing object

before XML

when the object property values ​​are null Serializer

does not add this element. How do I add this element to XML with an empty value?

eg:

[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;}
}

      

Serialization class

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();
        }
    }
}

      

Syntactic

var emp = new Employee();
emp.SerializeObject();

      

Actual output:

<?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" />

      

Expected Result:

<?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>

      

Any ideas?

Edited after comment:

When changed, the IsNullable=true

output looks something like the following.

<?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>

      

+3


source to share





All Articles