Ben
Ben

Reputation: 3912

XPATH returning no results

I have an loaded some XML in an XMLDocument object. I am iterating through the document by using an

For Each node As XmlNode In doc.GetElementsByTagName("Item", [NAMESPACE])
   'Do Stuff
Next

I would like to use xpath within this loop to pull out all nodes with the name of "MyNode" I would have thought i would simply have to do node.SelectNodes("MyNode"), but this returns a list of zero.

<Root>
<Item>
<MyNode></MyNode>
<MyNode></MyNode>
<MyNode></MyNode>
<RandomOtherNode></RandomOtherNode>
<RandomOtherNode></RandomOtherNode>
</Item>
<MyNode></MyNode>
<MyNode></MyNode>
<MyNode></MyNode>
<RandomOtherNode></RandomOtherNode>
<RandomOtherNode></RandomOtherNode>
<Item>
</Item>
<Item>
<MyNode></MyNode>
<MyNode></MyNode>
<MyNode></MyNode>
<RandomOtherNode></RandomOtherNode>
<RandomOtherNode></RandomOtherNode>

</Item>
</Root>

Do i have to do something extra?

Upvotes: 1

Views: 887

Answers (3)

Les
Les

Reputation: 10595

An XPATH of "MyNode" should work, my guess is your [NAMESPACE] is wrong. Try calling GetElementsByTagName() without the NAMESPACE. Either that, or look at the code in your loop and make sure you don't have a malformed WriteLine() or something.

Please excuse the following C# example as I seldom use VB. It demonstrates that your XPATH is correct...

string xml = @"
<Root> 
    <Item> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <RandomOtherNode></RandomOtherNode> 
        <RandomOtherNode></RandomOtherNode> 
    </Item> 
    <MyNode></MyNode> 
    <MyNode></MyNode> 
    <MyNode></MyNode> 
    <RandomOtherNode></RandomOtherNode> 
    <RandomOtherNode></RandomOtherNode> 
    <Item> 
    </Item> 
    <Item> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <RandomOtherNode></RandomOtherNode> 
        <RandomOtherNode></RandomOtherNode> 

    </Item> 
</Root> 
";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        foreach (XmlNode node in doc.GetElementsByTagName("Item"))
        {
            foreach (XmlNode n2 in node.SelectNodes("MyNode"))
                Console.WriteLine("{0}:{1}", node.Name, n2.Name);
        }

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062492

Try "//MyNode" , or "descendant::MyNode"

Upvotes: 0

florin
florin

Reputation: 405

To get all MyNode you can use doc.DocumentElement.SelectNodes("//MyNode") or even better doc.DocumentElement.SelectNodes("/Root/Item/MyNode")

Upvotes: 1

Related Questions