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"); ???
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With