I read that Nodes
() emits all the nodes including sub.
and DescendantNodes
() the same but in a recursive way.
however - I cant find any situation in which i will need the recursive way...
When should I prefer working with DescendantNodes
() over Nodes
() ?
i.e :
IEnumerable<XNode> nodes =from nd in xmlTree.DescendantNodes()
select nd;
foreach (XNode node in nodes)
Console.WriteLine(node);
output :
question :
Why will i need it recursively splitted ,when I can work with Nodes() ?
Well nodes gives you the child nodes of the node you call it on while descendantnodes gives you the descendant nodes of the node you call it on.
Imagine you have an XML document you want to process with several levels of nesting and you want to find all comment nodes at all levels, then you can do
XDocument doc = XDocument.Parse(@"<!-- comment 1 -->
<root>
<!-- comment 2 -->
<foo>
<!-- comment 3 -->
<bar><!-- comment 4 --></bar>
</foo>
</root>
<!-- comment 5 -->");
foreach (XComment comment in doc.DescendantNodes().OfType<XComment>())
{
Console.WriteLine(comment.Value);
}
If you solely used the Nodes
method you would need to write a recursive method to find all comment nodes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With