I'm serializing a class into an XML document and I want to understand how to add a custom attribute to multiple fields of the class. I know we can use [XMLAttribute(AttributeName="CustomAttribute"] to add a custom attribute to a single node of an XML document, but I can't figure out how to add a custom attribute to multiple nodes.
My class is as follows:
[XmlRoot(ElementName = "customer")]
public class Customer
{
[XmlElement(ElementName = "cust_id")]
public string CustomerId {get; set;}
[XmlElement(ElementName = "cust_name")]
public string CustomerName {get; set; }
[XmlElement(ElementName = "cust_phone")]
public string CustomerPhone {get; set; }
[XmlElement(ElementName = "cust_email")]
public string CustomerEmail {get; set; }
}
And, I'm using the following code to serialize the class into XML:
var xmlSerializer = new XmlSerializer(toSerialize.GetType());
using (var textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
After serializing the above class, I get the following XML:
<customer>
<cust_id>1</cust_id>
<cust_name>John</cust_name>
<cust_phone>12345678</cust_phone>
<cust_email>john@gmail.com</cust_email>
</customer>
Now, in case if any of the fields of the customer class are null, I want to mark the respective XML nodes as IsNull = "TRUE". For Example:
<customer>
<cust_id>1</cust_id>
<cust_name>John</cust_name>
<cust_phone IsNull = "TRUE" />
<cust_email IsNull = "TRUE" />
</customer>
How can we serialize a class into XML like above so that custom attributes are set for multiple nodes of an XML document?
Thank You,