C# : Getting all nodes of XML doc

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);

see here: Iterating through all nodes in XML file

shortly:

 string xml = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }

In my opinion the simplest solution is using XPath. Also this works if you have .NET 2:

var testDoc = new XmlDocument();
testDoc.LoadXml(str);
var tmp = testDoc.SelectNodes("//*"); // match every element

Tags:

C#

Xml