LINQ to XML vs. XML DOM, XMLDOM and LINQ to XML with Lambda Expression

There a numerous reasons why you would need to create an XML file. Configuration settings or using it as a data source are 2 examples. In both cases, you would need to create the XML file. If you have never done it before then the first question is, How do I create, read and modify the file. The second question you may ask, after doing some research, is which route should I go? Should I use XMLDOM or LINQ to XML. Many years ago I used XMLDOM to write a program that exchanged information using an XML file. This was before LINQ to XML. XMLDOM is the older model and LINQ to XML is the new. Everything I needed to do with the creation, reading and modification of an XML file is possible with LINQ to XML. And you can read, write and modify a file created by LINQ to XML with XMLDOM and vice-versa. I will use LINQ to XML for all my XML activities from now on.

Creating an XML file using LINQ to XML

Compared to XMLDOM, writing an XML file is much easier. It takes less code and the code itself is easier to read and understand.

[sourcecode language="csharp"]
XElement L2XML =
  new XElement("configuration",
    new XElement("default",
      new XAttribute("key", "language"),
      new XAttribute("value", "de-DE") 
    )
  );
 
L2XML.Save("L2XML.xml");
[/sourcecode]

The above code creates a file like this.

[sourcecode language="csharp"]
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <default key="language" value="de-DE" />
</configuration>
[/sourcecode]

Reading or Selecting data within an XML file using LINQ to XML

NOTE: Before you try to modify a file, it is always a good idea to check if the file exists. If you don’t confirm you will encounter an exception. Use the System.IO.File.Exists method to get confirmation.

Before you add a new element or modify an existing you may want to check if it already exists. I use LINQ to XML with a Lambda Expression to do this.

[sourcecode language="csharp"]
return XElement.Load("L2XML.xml")
        .Elements("default")
        .Where(el => el.Attribute("key").Value == "language")
        .Select(el => el.Attribute("value").Value)
        .Single();
[/sourcecode]

In this example a System.String variable will be returned with a value of de-DE. I also use the Single() method as I expect that the key will exist only once. If the key exists more than once and the Single() method is used, the an exception will be thrown. If you want to receive multiple rows, then remove the Single() and loop through the result using a foreach statement. After we are sure the XML file exists and whether the key exists, we can then add or modify the element. You should put this within a try…catch block, because if it is not found it will throw a InvalidOperationExecption.

Modifying an XML file using LINQ to XML

NOTE: Before you try to modify a file, it is always a good idea to check if the file exists. If you don’t you will encounter an exception. Use the System.IO.File.Exists method for this.

Add an Element using LINQ to XML

[sourcecode language="csharp"]
XElement xmlDoc = XElement.Load("L2XML.xml");                  
XElement newQuery =
  new XElement("default",
    new XAttribute("key", "language"),
    new XAttribute("value", "es-ES")
  );
xmlDoc.Add(newQuery);
xmlDoc.Save("L2XML.xml");
[/sourcecode]

Modify an existing elements value using LINQ to XML

If your program determines that the key already exists, then you would probably want to update the value of the key. Again, I use LINQ to XML with a Lambda Expression to perform the update.

[sourcecode language="csharp"]
xmlDoc.Elements("default")
      .Where(el => el.Attribute("key").Value == "language")
      .Single()
      .SetAttributeValue("value", "fr-FR");
xmlDoc.Save("L2XML.xml");
[/sourcecode]

It is always a good idea to put your code into try…catch blocks just in case there is a problem. If you do this, always notify the user that there was a problem. And give them enough information to solve the error themselves. At a minimum, provide enough for level 1 or level 2 support to provide the solution.

Download the source




Leave a Comment

Your email address will not be published.