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>&开发者_开发技巧lt;/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?
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);
}
To get all MyNode you can use doc.DocumentElement.SelectNodes("//MyNode") or even better doc.DocumentElement.SelectNodes("/Root/Item/MyNode")
Try "//MyNode" , or "descendant::MyNode"
精彩评论