Programming - XML and LINQ
With .NET 3.5, we are provided with LINQ. Its features can be applied to loads of different things including SQL, objects, lists and XML.
The XML one is worth looking at.
A small example is provided below:
An XML snippet could look like this:
1: <?xml version="1.0" encoding="utf-8" standalone="yes"?>
2: <!-- A Comment in the XML -->
3: <persons>
4: <person>
5: <firstName>Martin</firstName>
6: <lastName>Mihaylov</lastName>
7: <address city="Sofia" country="Bulgaria" />
8: </person>
9: </persons>
The class we ae looking to serialize the XML into could look like this:
1: public class Person
2: {
3: public string FirstName { get; set; }
4: public string LastName { get; set; }
5: public Location Address { get; set; }
6: }
7:
8: public class Location
9: {
10: public string Country { get; set; }
11: public string City { get; set; }
12: }
To create the above XML, w would run the following:
1: Person p1 = new Person()
2: { 3: FirstName = "Martin",
4: LastName = "Mihaylov",
5: Address = new Location()
6: { 7: City = "Sofia",
8: Country = "Bulgaria"
9: }
10: };
andwith this object, we can write our teh XML schema as follows:
1: XElement persons =
2: new XElement( "persons",
3: new XElement( "person",
4: new XElement( "firstName", p1.FirstName ),
5: new XElement( "lastName", p1.LastName ),
6: new XElement( "address",
7: new XAttribute( "city", p1.Address.City ),
8: new XAttribute( "country", p1.Address.Country ) ) ) );
We would then write out our XML file:
1: XDocument myXml = new XDocument( new XDeclaration( "1.0", "utf-8", "yes" ),
2: new XComment( "A Comment in the XML" ), persons );
and
And to deserialize the XML we would use the following LINQ:
and 1: List<Person> personsList =
2: ( from person in myXml.Descendants( "person" )
3: where (( string )person.Element( "address" ).Attribute( "country" )).Equals( "Bulgaria" )
4: select new Person()
5: {
6: FirstName = person.Element( "firstName" ).Value,
7: LastName = person.Element( "lastName" ).Value,
8: Address = new Location()
9: {
10: City = person.Element( "address" ).Attribute( "city" ).Value,
11: Country = person.Element( "address" ).Attribute( "country" ).Value
12: }
13: } ).ToList();
and
We would also have to load our XML file first:
and 1: XDocument myXML = XDocument.Load( "MyXML.xml" );