2

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,

  • Possible duplicate of [Serialize Property as Xml Attribute in Element](https://stackoverflow.com/questions/11330643/serialize-property-as-xml-attribute-in-element) – kara May 03 '19 at 11:56
  • Why do you want to mark it as `null`? Are you sure you want to differ between `null` and `String.Empty`? – kara May 03 '19 at 12:00
  • @kara Actually, I want to understand that is it is possible to create a custom attribute for more multiple nodes in an XML document. – Muhammad Imran Khan May 03 '19 at 15:02
  • Do you really want a custom attribute, or the w3 standard attribute [`xsi:nil`](https://www.w3.org/TR/xmlschema-1/#xsi_nil)? The latter is supported natively by `XmlSerializer`, see [Xsi:nil Attribute Binding Support](https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/ybce7f69(v=vs.100)). – dbc May 04 '19 at 05:30

0 Answers0