Trufa
Trufa

Reputation: 40717

How can I get all the nodes of a xml file?

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?

Upvotes: 0

Views: 6599

Answers (3)

svick
svick

Reputation: 244837

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.

Upvotes: 2

SCB
SCB

Reputation: 3084

Add

 using System.Xml.Linq;

Then you can do

var element = XElement.Parse({Your xml string});

    Console.Write(element.Descendants("Name").Select(el => string.Format("{0} {1}", el.Element("FirstName").Value, el.Element("LastName").Value)));

Upvotes: 0

MyGuruG
MyGuruG

Reputation: 21

There are several ways of doing it.

With XDocument and LINQ-XML

foreach(var name in doc.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct()) 
{ 
    Console.WriteLine(name); 
} 

If you are using C# 3.0 or above, you can do this

var data = XElement.Load("c:/test.xml"); // change this to reflect location of your xml file 
var allElementNames =  
(from e in in data.Descendants() 
select e.Name).Distinct();

Upvotes: 0

Related Questions