Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab All XML Elements of a Specific Type: Even nested elements

Tags:

c#

xml

I am parsing an XML document in C# ASP.NET. Is there a way/function that I don't know of to get all the elements of the tag "course"?

The format of the XML is like so:

<a>
  <g1>
    <course></course>
    <g9>
      <course></course>
      ... more course elements
    </g9>
    <course></course>
    <g2>
      <g3>
        <course></course>
        ...
      </g3>
    </g2>
  </g1>
</a>

When I do the following code I get back no "course" elements, is there a simple function that can grab all these elements in one go?

XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://kjkjkj.com");
XmlNodeList list = xdoc.DocumentElement.SelectNodes("course");

// if I debug: list.count = 0 but if I look at xdoc.DocumentElement.outerXml 
// its the correct XML so I did parse the file & get XML contents.

// Is there any C# equivalent of document.getElementsByTagName("course"); ???
like image 742
sazr Avatar asked Feb 24 '12 03:02

sazr


1 Answers

You were close:

XmlNodeList list = xdoc.DocumentElement.SelectNodes("//course");

Prefixing with // will grab all the nodes in the document named course, no matter where they are.

As an alternative you should consider parsing your XML with Linq to Xml which integrates nicely with Linq to objects. The equivalent syntax for the same there is

var courses  = xdoc.Descendants("course");
like image 123
BrokenGlass Avatar answered Oct 14 '22 17:10

BrokenGlass