Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from node with same name

I'd like to retrieve information from an XML file, however the way it's formatted is pretty strange. Here it is...

<?xml version="1.0"?>
<Careers>
    <CareerList>
        <CareerName></CareerName>
        <CareerDescription></CareerDescription>
    </CareerList>
    <CareerList>
        <CareerName>Cook</CareerName>
        <CareerDescription>Cooks food for people</CareerDescription>
    </CareerList>
</Careers>

I'd like to get the 2nd value, which would be Cook and the description which is Cooks food for people, but instead I'm getting only the empty node. For example...

    public string CareerDescription(string CareerFile)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(CareerFile);
        string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;
        return Description;
    }

How would I select the second node instead of the first?

like image 600
Waverunner Avatar asked Apr 14 '26 19:04

Waverunner


1 Answers

You can use an index in your XPath expression:

xmlDoc.SelectSingleNode("Careers/CareerList[2]/CareerDescription").InnerText

Personally I'd use LINQ to XML instead, mind you:

var doc = XDocument.Load(CareerFile);
return doc.Root
          .Elements("CareerList")
          .ElementAt(1) // 0-based
          .Element("CareerDescription")
          .Value;
like image 112
Jon Skeet Avatar answered Apr 16 '26 09:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!