How can i access the index of an XML Child using an XPathNavigator?
I want to create a compilestring to use it with an XPathExpression. I already navig开发者_如何学Pythonated to a subset and have created an iterator. Based on the current Position of that iterator I create a new currentNode. Now I want to create the exact expression which leads to that, and only that node, so I can then create an iterator which selects only these children.
public XPathNodeIterator extractSubChildIterator(XPathNavigator currentNode)
{
XPathNavigator nav = currentNode.Clone();
string myXPathString = "/"+ nav.LocalName + "["+ HOWDOIGETTHISNUMBER(nav) +"]";
while (nav.MoveToParent())
{
if (!(nav.Name == ""))
myXPathString = "/" + nav.LocalName + "[" + HOWDOIGETTHISNUMBER(nav) + "]" + myXPathString;
}
myXPathString += "/*";
XPathExpression expr = nav.Compile(myXPathString);
return currentNode.Select(expr);
}
The function HOWDOIGETTHISNUMBER() is the placeholder for the thing I don't quite get. I base my expression String on the examplelist on This Page - "/catalog/cd[1] selects the first cd child of catalog"
string myXPathString = "/"+ nav.LocalName + "["+ HOWDOIGETTHISNUMBER() +"]";
You want to construct and evaluate this XPath expression:
"count(preceding-sibling::*[name()=''" + nav.LocalName +"]"
The Tip to Evaluate an XPathExpression was the right one. Various Expressions can be found here. Problem solved using this query:
private string HOWDOIGETTHISNUMBER(XPathNavigator theNode)
{
XPathExpression query = theNode.Compile("count(preceding-sibling::"+theNode.LocalName+")+1");
return theNode.Evaluate(query).ToString();
}
精彩评论