btzs
btzs

Reputation: 1108

Get Access to XMLNode

i want to read some values of an XML File. I'm able to read some values, but I want to get the Information between the <tools></tools>-tags.

XmlNodeList xnList = xml.SelectNodes("/instructions/Steps");
foreach (XmlNode xn in xnList)
{

    XmlNodeList xnChildList = xn.ChildNodes;
    foreach (XmlNode xnc in xnChildList)
    {
        MessageBox.Show("ID: " + xnc["ID"].InnerText + "Desc: " + xnc["desc"].InnerText);
        //this one is working so far!


        //I tried to create a new XMLNodeList

        XmlNodeList testNodeList = xnc.SelectNodes("/tools");
        foreach (XmlNode node in testNodeList)
        {
            MessageBox.Show(node["tool"].InnerXml);
        }
    }
}

But it's not working. How can I address the tools-section?

XML file looks like this:

<instructions>
    <Steps QualificationID="12,3">
                <Step>
                    <ID>1.1</ID>
                    <desc>desc</desc>
                    <tools>
                        <tool ID = "1" name = "10Zoll Steckschl" />
                        <tool ID = "2" name = "5Zoll Steckschl" />
                    </tools>
                </Step>
                <Step>
                    <ID>1.2</ID>
                    <desc>desc2</desc>
                    <tools>
                        <tool ID = "3" name = "11Zoll Steckschl" />
                        <tool ID = "4" name = "54Zoll Steckschl" />
                    </tools>
                </Step>
    </Steps>
    <Steps QualificationID="1223,3">
                <Step>
                    <ID>2.1</ID>
                    <desc>desc3</desc>
                    <tools>
                        <tool ID = "5" name = "14Zoll Steckschl" />
                        <tool ID = "6" name = "2Zoll Steckschl" />
                    </tools>
                </Step>
                <Step>
                    <ID>2.2</ID>
                    <desc>desc4</desc>
                    <tools>
                        <tool ID = "7" name = "13Zoll Steckschl" />
                        <tool ID = "8" name = "4Zoll Steckschl" />
                    </tools>
                </Step>
    </Steps>
</instructions>

Upvotes: 0

Views: 71

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500805

I strongly suspect this is the problem:

XmlNodeList testNodeList = xnc.SelectNodes("/tools");

The leading slash is taking it back up to the root node - you only want to look for tools elements under xnc:

XmlNodeList testNodeList = xnc.SelectNodes("tools");

This sort of thing is why I'd personally prefer to use LINQ to XML :)

XDocument doc = ...;
foreach (var step in doc.Root.Elements("Steps").Elements("Step"))
{
     MessageBox.Show(string.Format("ID: {0} Desc: {1}",
                     step.Element("ID").Value, step.Element("desc").Value);

     foreach (var tool in step.Elements("tools"))
     {
         ...
     }
}

Upvotes: 1

Related Questions