How to Deserialize XML array to string[] in C#

By FoxLearn 1/14/2025 8:56:58 AM   39
To deserialize an XML array into a string[] type, you can use the XmlArray and XmlArrayItem attributes.

How to deserialize an XML array into a string[] type?

For example, Consider the following XML structure where an array is represented by a series of <item> elements:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <MyXml>
      <Id>657467</Id>
      <MyArray>
        <item>Apple</item>
        <item>Banana</item>
        <item>Cherry</item>
      </MyArray>
   </MyXml>
</root>

Here, MyArray would typically be deserialized into a cumbersome class:

// I don't want this class
[XmlRoot(ElementName="MyArray")]
public class MyArray 
{
  [XmlElement(ElementName="item")]
  public List<string> Item { get; set; }
}

However, if you simply want a string[] array, the solution is to use the XmlArray and XmlArrayItem attributes. These attributes guide the XmlSerializer to treat the XML structure as an array:

[XmlArray(ElementName = "MyArray", IsNullable = true)]
[XmlArrayItem(ElementName = "item", IsNullable = true)]
public string[] MyArray 
{
  get; set;
}

The XmlArray attribute tells the serializer that MyArray represents an array, and the XmlArrayItem attribute specifies that each individual item in the array corresponds to an <item> element in the XML.

Now, the XmlSerializer can deserialize the XML directly into a string[]:

string contents = "this is my xml string";

XmlSerializer serializer = new XmlSerializer(typeof(MyXml));
using (TextReader reader = new StringReader(contents))
{
  var obj = (MyXml)serializer.Deserialize(reader);
}

Why is this important?

This becomes especially useful when working with both XML and JSON data formats. You may want to avoid having to define complex structures just to handle the XML array format.

For example, consider the following JSON structure:

"MyArray": {
  "item": [
    "Apple",
    "Banana",
    "Cherry"
  ]
}

Instead of creating an additional class to deal with this structure, you can use attributes for both XML and JSON serialization in your POCO class:

[JsonProperty(PropertyName = "MyArray")]
[XmlArray(ElementName = "MyArray", IsNullable = true)]
[XmlArrayItem(ElementName = "item", IsNullable = true)]
public string[] MyArray 
{
  get; set;
}

With this setup, you can deserialize JSON arrays using the standard JSON array notation:

"MyArray": [    
    "Apple",
    "Banana",
    "Cherry"
]

This allows for smooth interoperability between XML and JSON without needing extra code for different data formats.