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.

New way

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

Remove element

Old way

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

New way

The Remove method is conveniently available in the child element.

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.

New way

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

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.

New way

Querying is easy as we use a familiar syntax.

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

Comparing LINQ to XML versus XMLDOM
Tagged on: