I am now learning XmlDocument but I\'ve just ran into XDocument and when I try to search the difference or benefits of them I can\'t find something useful, could you please
As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument
, and the XNamespace ns + "elementName"
syntax makes for pleasurable reading when dealing with namespaces.
One thing worth mentioning for xsl
and xpath
die hards to note is that it IS possible to still execute arbitrary xpath 1.0
expressions on Linq 2 Xml XNodes
by including:
using System.Xml.XPath;
and then we can navigate and project data using xpath
via these extension methods:
For instance, given the Xml document:
<xml>
<foo>
<baz id="1">10</baz>
<bar id="2" special="1">baa baa</bar>
<baz id="3">20</baz>
<bar id="4" />
<bar id="5" />
</foo>
<foo id="123">Text 1<moo />Text 2
</foo>
</xml>
We can evaluate:
var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");