sazr
sazr

Reputation: 25938

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

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

Upvotes: 5

Views: 3552

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160952

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

Upvotes: 9

Related Questions