Comparing LINQ to XML versus XMLDOM

LINQ to XML allows to manipulate XML documents using the familiar LINQ syntax. It is available in System.Xml.Linq assembly. Prior to LINQ, the classes in System.Xml assembly were used to manipulate XML documents. In this post, we will compare the newer LINQ to XML assembly with the older assembly.

 

Create element

Old way

XmlDocument class is central to System.Xml assembly. It has static methods, CreateElement and CreateAttribute to create a new element.

XmlElement elem = XmlDocument.CreateElement("Employee");
XmlAttribute attr = XmlDocument.CreateAttribute("EmpID");
attr.Value = "100";
elem.Attributes.Add(attr);

New way

XElement and XAttribute classes are available in System.Xml.Linq assembly. Create a new element with lesser code using these classes.

XElement elem = new XElement("Employee",
               new XAttribute("EmpID", 100));

Remove element

Old way

In System.Xml assembly, removing a child requires both the parent and child to be available.

parent.Remove(child);

New way

The Remove method is conveniently available in the child element.

child.Remove();

Set optional attributes

Old way

With XmlDocument, setting optional attributes is a pain. Test for the presence of attribute. And, conditionally create the attribute or update it.

XmlAttribute attr = elem.Attributes("EmpID");
if(attr!=null)
{
    attr = XmlDocument.CreateAttribute("EmpID");    
}
attr.Value = "100";

New way

XElement class has the SetAttributeValue. It creates a new attribute, if not available.

elem.SetAttributeValue("EmpID", 100);

Queries

Old way

XPath is very useful to query XML document. XmlDocument class the SelectSingleNode and SelectNodes method to query the document. Though XPath is elegant, we have to learn a new syntax.

XmlNode emp = XmlDocument.SelectSingleNode("/Employees/Employee[@id=100]");

New way

Querying is easy as we use a familiar syntax.

var qry = from elem in root.Elements("Employee")
                where elem.Attribute("EmpID").Value == 100
                select elem;

XElement emp = qry.First();

In my opinion, LINQ to XML provides a simpler API to query and manipulate XML documents. Newer is better!

Related Posts

Leave a Reply

Your email address will not be published.