C# – How to get all the nodes of a xml file

cnodesparsingxml

Let's say I have this XML file:

<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

And now I want to print all the names of the node:

Names
Name
FirstName
LastName

I managed to get the all in a XmlNodeList, but I dont know how SelectNodes works.

XmlNodeList xnList = xml.SelectNodes(/*What goes here*/);

I want to select all nodes, and then do a foreach of xnList (Using the .Value property I assume).

Is this the correct approach? How can I use the selectNodes to select all the nodes?

Best Answer

Ensuring you have LINQ and LINQ to XML in scope:

using System.Linq;
using System.Xml.Linq;

If you load them into an XDocument:

var doc = XDocument.Parse(xml);    // if from string
var doc = XDocument.Load(xmlFile); // if from file

You can do something like:

doc.Descendants().Select(n => n.Name).Distinct()

This will give you a collection of all distinct XNames of elements in the document. If you don't care about XML namespaces, you can change that to:

doc.Descendants().Select(n => n.Name.LocalName).Distinct()

which will give you a collection of all distinct element names as strings.