I have an xml file with the following format
<someXML>
<a>
<b></b>
<b test='someValue'></b>
</a>
<c>
<d test='someOtherValue'></d>
<d></d>
</c>
</someXML>
I’m trying to write C# code that will get me a node set containing only those nodes with the test attribute. I am trying to use an XPathExpression in this manner:
XDocument document = XDocument.Load("someXML");
XPathNavigator navigator = document.CreateNavigator();
XPathExpression expression = XPathExpression.Compile("//*[@test]");
object nodeSet = navigator.Evaluate(expression);
This doesn’t seem to be working. When I debug, the nodeSet always contains the Root element. Is there something wrong with the expression or is this working correctly?
Thanks!
Do you assume that the
nodeSetcontains the “Root” element because the debugger displays its string representation asPosition=0, Current={Root}? That may be misleading; the reason that the “Root” element appears is because theXPathNodeIterator(which is the actual type returned byEvaluatein your case) has not yet been positioned on the first node resulting from the query. Per the MSDN documentation forXPathNodeIterator:You can retrieve your path items by iterating over your
nodeSet:Or, if you want them converted to an array: