tags:

views:

43

answers:

3

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?

+1  A: 

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

florin
//MyNode will get all MyNode elements in the document, even if the current node (for node.SelectNodes("//MyNode")) is an "Item". I.e., using //MyNode will return 9 nodes, while the OP is looking for six.
Les
My bad, did not see the "MyNode" outside the "Item" node. Use full node path...
florin
A: 

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

Marc Gravell
See my comment on //MyNode above. "descendant::MyNode" would work.
Les
+2  A: 

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);
        }
Les