This article is compatible with the latest version of Silverlight.
When working with data, it often comes in an XML format. So we have to serialize and deserialize it in order to use it. There are several ways of doing that – for example: DOM, XQuery, XSLT. DOM is the oldest from the three, but still can do the work. XQuery and XSLT are not very easy to use and require some time to master. In .NET 3.5 a big programming model improvement was made with the LINQ - Language-Integrated Query. It can be used for objects, databases and XML. In the following article I will try to explain the basics of using LINQ to XML and if you are new to it, I hope it will help you to improve your programming experience.
Introduction
LINQ to XML allows us to create, read and edit XML files and what’s more important - it’s done in a very easy and understandable way. To use LINQ to XML you should add a reference to the System.Xml.Linq.dll (for the XDocument and the other classes) and use the System.Linq namespace (for the LINQ syntax).
A brief overview of the most important methods of XElement and XDocument
- Add(object content) – adds the new content as a child of the element
- Remove() – Remove this element from its parent
- Descendents( XName name ) – returns a collection of all descendents of this element, which names match the argument, in document order
- Element( XName name ) – returns the first child that has a matching name
- Elements( XName name ) - returns a collection of all children of this element, which name matches the argument, in document order
- Nodes() – returns a collection of all children of the current element in document order
Creating an XML file
So let’s have a simple class Person:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Location Address { get; set; }
}
public class Location
{
public string Country { get; set; }
public string City { get; set; }
}
And we create an object of type Person:
Person p1 = new Person()
{
FirstName = "Martin",
LastName = "Mihaylov",
Address = new Location()
{
City = "Sofia",
Country = "Bulgaria"
}
};
Now let’s try to create an XML from it. For that purpose we use XElement and XAttribute objects:
XElement persons =
new XElement( "persons",
new XElement( "person",
new XElement( "firstName", p1.FirstName ),
new XElement( "lastName", p1.LastName ),
new XElement( "address",
new XAttribute( "city", p1.Address.City ),
new XAttribute( "country", p1.Address.Country ) ) ) );
We simply create an element “persons” using the XElement object and then nest other elements in it. We can also create properties for the elements thanks to the XAttribute object. We can also use the XDeclaration object to define our xml document and XComment to add a comment to the xml document. Here it is:
XDocument myXml = new XDocument( new XDeclaration( "1.0", "utf-8", "yes" ),
new XComment( "A Comment in the XML" ), persons );
So the final output should look like this:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- A Comment in the XML -->
<persons>
<person>
<firstName>Martin</firstName>
<lastName>Mihaylov</lastName>
<address city="Sofia" country="Bulgaria" />
</person>
</persons>
Adding an element to the XDocument
First we find the element we want to add something to and then we use its Add method to add our new element. Here is an example:
myXml.Element( "persons" ).Add( new XElement( "person",
new XElement( "firstName", p2.FirstName ),
new XElement( "lastName", p2.LastName ),
new XElement( "address",
new XAttribute( "city", p2.Address.City ),
new XAttribute( "country", p2.Address.Country ) ) ) );
Removing an element form the XDocument
To remove an element or attribute you must navigate to the desired element and then call its Remove method:
myXml.Element( "persons" ).Element( "person" ).Remove();
This will remove the first element with name “person” in “persons”.
Reading an XML file
Before reading you should load your XML file to an XElement or XDocument object. This can be done with the Load method. You can input from string, from TextReader, from XMLReader and of course from file. Here is an Example:
XDocument myXML = XDocument.Load( "MyXML.xml" );
Now let’s try to read the contents of an XML file. For this example we use the XML string we’ve already created in the beginning of the article. Thanks to LINQ we can use the standard query operators: from, in, select. Because of that to take the information you need from an XML file becomes fairly easy:
List<Person> personsList =
( from person in myXml.Descendants( "person" )
where (( string )person.Element( "address" ).Attribute( "country" )).Equals( "Bulgaria" )
select new Person()
{
FirstName = person.Element( "firstName" ).Value,
LastName = person.Element( "lastName" ).Value,
Address = new Location()
{
City = person.Element( "address" ).Attribute( "city" ).Value,
Country = person.Element( "address" ).Attribute( "country" ).Value
}
} ).ToList();
The Descendants method returns all child elements that have name “person” (in our case). Then from each descendent that has an "address" element with "country" property set to "Bulgaria" we create a new object of type Person and set its properties. The output is a list of objects.
References
http://msdn.microsoft.com/en-us/library/bb308960.aspx - probably almost everything about LINQ to XML you want to know ... and more
http://msdn.microsoft.com/en-us/library/cc645034(VS.95).aspx - How to: Load an XML File from an Arbitrary URI Location
http://msdn.microsoft.com/en-us/library/cc189044(VS.95).aspx - How to: Create Dynamic XAML with LINQ to XML
Summary
These are just the basics of using LINQ to XML. It’s really easy learning the basics of it, but there is a lot more and if I write it here it will make the article more complicated and heavier. The main purpose of the article is to be a quick start for people have just begun using this technology. So maybe I’ll write additional articles about LINQ to XML which will take a deeper look in it. If you are impatient and want to learn more now just take a look at the references above.