In-Depth

Serialize Arrays and ArrayLists to XML

The XmlSerializer class provides a great way to convert objects to XML and back. However, it can be difficult to serialize collections such as Arrays and ArrayLists properly unless you know a few tricks.

Technology Toolbox: XML

The XmlSerializer class provides a great way to convert (serialize) objects to XML and back (deserialize). However, it can be difficult to serialize collections such as Arrays and ArrayLists properly unless you know a few tricks.

This sample application demonstrates how you can add multiple Car class instances into an Array as well as an ArrayList, then serialize them into an XML structure. You can accomplish this serialization process by using special XML serialization attributes such as XmlArray and XmlArrayItem, found in the System.Xml.Serialization namespace. For example, this code demonstrates how you can identify the type within an ArrayList using the XmlArrayItem attribute along with the C# typeof keyword:

[XmlArray("carsArrayList")]
[XmlArrayItem("car",typeof(Car))]
public ArrayList CarsCollection {
   get {
      return _CarsList;
   }
   set {
      _CarsList = value;
   }
}

Here's the output generated by serializing the ArrayList:

<?xml version="1.0" encoding="utf-16"?>
<carsCollection xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <carsArrayList>
      <car>
         <license>1234</license>
         <color>Black</color>
      </car>
      <car>
         <license>4321</license>
         <color>Blue</color>
      </car>
   </carsArrayList>
</carsCollection>

Download the sample here. To view a live example, visit the XML for ASP.NET Developers Web site.

Featured

  • Attackers Using Excel Read-Only Files To Obscure Malware

    Attackers can attempt to hide malicious payloads in Excel files sent by e-mail by using a standard Excel feature, according to a Tuesday post by Mimecast researchers.

  • Microsoft 365 Personal and Family Product Unveiled

    Microsoft on Monday announced new "Microsoft 365 Personal and Family subscriptions" to come next month, a new single consumer product providing access to applications such as Excel, PowerPoint and Word.

  • Microsoft Shifting Away from Office 365 Brand Name in April

    Microsoft on Monday announced coming product naming changes, where "Office 365" is mostly getting replaced by the "Microsoft 365" brand.

  • Microsoft Grows Services Amid COVID-19

    Microsoft in a Saturday announcement recapped how its services have been affected by "shelter-in-place" governmental mandates in the last week, providing details on growth stats and prioritizations.

comments powered by Disqus

Office 365 Watch

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.