Using Linq, it’s easily possible to query various types of data like sql database, xml, objects like DataTable, ArrayList. It’s also possible to transform data into other formats like xml using linq. In this article, I will demonstrate how to query an System.Collections.ArrayList collection and then to save the data in xml format.
At first, I will create an ArrayList object and add Person objects to it. The code to do is below.
The Person class has 4 public properties of different data types – string, DateTime and int as shown below.
Person objects are added to the ArrayList list which can be queried using linq as shown in my previous post on query ArrayList using Linq. While querying the list, System.Xml.Linq.XElement objects can be created which can be saved as xml using System.Xml.Linq.XDocument’s Save() method. The code to show this is below.
As can be seen, the ArrayList object is queried for Person objects. This is not really needed for the code to work but is an example on how objects can be queried from ArrayList.
Using another query, “query”, XElement objects are created. The names of the XElement – that is, the names of the xml elements are arbitrary and the value of the elements are obtained from the Person object. The XElement objects are then added to XDocument object and saved as xml using XDocument.Save() method. The resultant xml looks like below.
One thing to note is that the xml declaration is automatically added. DateTime field – DateOfBirth is automatically converted to its string representation.
The xml produced previously contains elements only. The Linq query could be easily updated to change the data to be the attributes of xml elements. This is shown in another query – “query2”. System.Xml.Linq.XAttribute objects are created similarly instead of XElement objects and added to XElement object which is then added to XDocument object and saved as xml. The resultant xml file looks like below.
The data looks similar to the previous xml except that they are now attributes of “Person” element instead of child elements.