LINQ to XML

The System.Xml.Linq namespace offers an easily and efficiently way to create, read and modify XML documents. Within this article I want to show you the basic concept to create and read a XML document.

 
Create a XML document

In this example application a list of persons should be written into a XML document. Each person has a first name and last name property. Furthermore an id property exists. The XML element of one person should contain the identifier as attribute and two sub elements with the name properties.

<Person id="1">
  <Name>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
  </Name>
</Person>

 
The following source code shows a console application to create the XML document. Two person datasets will be written into the file.

XElement rootElement;
XElement person;
            
rootElement= new XElement("Persons");
 
person = new XElement("Person",
    new XAttribute("id", 1),
    new XElement("Name", 
        new XElement("FirstName", "John"),
        new XElement("LastName", "Doe")));

rootElement.Add(person);

person = new XElement("Person",
    new XAttribute("id", 2),
    new XElement("Name", 
        new XElement("FirstName", "Jane"),
        new XElement("LastName", "Doe")));

rootElement.Add(person);

using (StreamWriter writer = new StreamWriter("persons.xml"))
{
    writer.Write(rootElement.ToString());
}

 
The following XML document will be created.

<Persons>
  <Person id="1">
    <Name>
      <FirstName>John</FirstName>
      <LastName>Doe</LastName>
    </Name>
  </Person>
  <Person id="2">
    <Name>
      <FirstName>Jane</FirstName>
      <LastName>Doe</LastName>
    </Name>
  </Person>
</Persons>

 
Read a XML document

At next the previously created file should be read. The following source code shows an according example. Please note that the example does not contain any error handling. Within your projects you should add try-catch statements.

XDocument document;
List<XElement> persons;
XElement name;
XElement firstName;
XElement lastName;

//load xml document
document = XDocument.Load("persons.xml");

//get all persons
persons = (from person in document.Descendants("Person")
            select person).ToList();

//show all persons
foreach (XElement person in persons)
{
    name = person.Descendants("Name").ToList()[0];
    firstName = name.Descendants("FirstName").ToList()[0];
    lastName = name.Descendants("LastName").ToList()[0];

    Console.WriteLine(
        person.Attribute("id").Value + ": " +
        firstName.Value + " " + 
        lastName.Value);
}

Console.ReadKey();

 
Summary

The System.Xml.Linq namespace offers efficiently classes and functions to handle XML documents. With this functions it is possible to read, write and modify XML documents.

Dieser Beitrag wurde unter .NET, C#, LINQ abgelegt und mit , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Hinterlasse einen Kommentar