Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : Getting all nodes of XML doc

Tags:

c#

xml

Is there a simple way, to get all nodes from an xml document? I need every single node, childnode and so on, to check if they have certain attributes.

Or will I have to crawl through the document, asking for childnodes?

like image 370
Nicolai Avatar asked Sep 19 '11 07:09

Nicolai


1 Answers

In LINQ to XML it's extremely easy:

XDocument doc = XDocument.Load("test.xml"); // Or whatever
var allElements = doc.Descendants();

So to find all elements with a particular attribute, for example:

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute("foo") != null);

That's assuming you wanted all elements. If you want all nodes (including text nodes etc, but not including attributes as separate nodes) you'd use DescendantNodes() instead.

EDIT: Namespaces in LINQ to XML are nice. You'd use:

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute(XNamespace.Xmlns + "aml") != null);

or for a different namespace:

XNamespace ns = "http://some.namespace.uri";

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute(ns + "foo") != null);
like image 59
Jon Skeet Avatar answered Sep 30 '22 20:09

Jon Skeet