LINQ to XML versus XMLDOM
I have been trying out LINQ to XML and I am impressed with the improvements made over XML DOM. In this post, I will illustrate a few nice features where LINQ scores over DOM.
Creation of elements
To create a new element in DOM, the following code should be written:
XmlElement elem = XmlDocument.CreateElement("Employee"); XmlAttribute attr = XmlDocument.CreateAttribute("EmpID"); attr.Value = "100"; elem.Attributes.Add(attr);
The code is simpler in the case of LINQ:
XElement elem = new XElement("Employee", new XAttribute("EmpID", 100));
Adding elements as first node
In DOM, this takes quite a few steps. In LINQ, it is simpler with the AddFirst method: parent.AddFirst(child);
Removing elements is elegant
Removing elements in DOM is something like this: parent.Remove(child); In LINQ, removing a child element is done on the child element itself: child.Remove();
Setting optional attributes
In DOM, this is quite complex:
XmlAttribute attr = elem.Attributes("EmpID"); if(attr!=null) { attr = XmlDocument.CreateAttribute("EmpID"); } attr.Value = "100";
In LINQ, this is a one liner: elem.SetAttributeValue("EmpID", 100);
Querying and XPath
In XML DOM, XPath was very useful to select elements:
XmlNode emp = XmlDocument.SelectSingleNode("/Employees/Employee[@id=100]");
Using LINQ is slightly longer. But the code is readable and it does not require a new skillset (XPath).
var qry = from elem in root.Elements("Employee") where elem.Attribute("EmpID").Value == 100 select elem; XElement emp = qry.First<xelement>();</xelement>
Overall, LINQ 2 XML supersedes DOM in capability and readability. The only disadvantage is that LINQ 2 XML does not support entities.
Category : ASP.NET


