Wednesday 22 July 2015

Ignore property to be serialized in xml serializer

Conditionaly ignore any property to be serialized in xml using XML serializer. You can achieve it using ShouldSerialize{Property Name} method. E.g
 
        public string PropertyName { get; set; }
        public bool ShouldSerialize PropertyName ()
        {
    // Condition for property which return true/false
               return !string.IsNullOrEmpty(PropertyName); 
        }
 
 
 
Serializable class :
 
[XmlRoot("TestXML")]
    public class Testxml
    {
        [XmlElement]
        public int Id { get; set; }
 
        [XmlElement]
        public string Name { get; set; }
 
        [XmlElement]
        public string City { get; set; }
        public bool ShouldSerializeCity()
        {
            return !string.IsNullOrEmpty(City);
        }
    }
 
Method to serialize :
 
Testxml xml = new Testxml();
xml.Id= 10;
xml.Name = "Ajay";
xml.City = "";
XmlSerializer ser = new XmlSerializer(typeof(Testxml));
StringWriter sw = new StringWriter();
ser.Serialize(sw, xml);
 
Results :
 
When  xml.City = "Kalol"; Then XML looks like below :
 
<?xml version="1.0" encoding="utf-16" ?>
<testxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <id>10</id>
    <name>Ajay</name>
    <city>Kalol</city>
</testxml>
 
When  xml.City = ""; Then XML looks like below :
 
<?xml version="1.0" encoding="utf-16" ?>
<testxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <id>10</id>
    <name>Ajay</name>
</testxml>

No comments:

Post a Comment