What's wrong with my Xpath?
I have an xml file and I am trying to get a list of all of a particular node using c#.
A trimmed down version of my xml is:
<file>
<AnotherNode>
</AnotherNode>
<ROWS>
<row>
<code>Code1</code>
<R>1</R>
<G>2</G>
<B>3</B>
</row>
<row>
<code>Code2</code>
<R>1</R>
<G>2</G>
<B>3</B>
</row>
</ROWS>
</file>
There are multiple "row" nodes and I want a list of all the codes from within those nodes
The XPath I am u开发者_开发技巧sing is:
/file/ROWS/row/code
with this code:
XmlDocument doc = new XmlDocument();
doc.Load(xml);
XmlNode root = doc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes(xpath here);
foreach (XmlNode code in nodeList)
{
}
but I am returning no nodes.
What am I doing wrong?
Thanks.
Remove the following line from your code:
root.InnerText = root.InnerText.ToLower();
This creates an XML with all tags in lower case and your XPath that is correct for the original tag names won't work anymore.
Solution and suggestion if you are using at least .net 3.5.
XDocument xdoc = XDocument.Load("XMLFile1.xml");
foreach (XElement element in xdoc.XPathSelectElements("//file/ROWS/row/code"))
{
}
Be sure to include "using System.Xml.XPath;"
Try removing this line from your code:
root.InnerText = root.InnerText.ToLower();
I tried converting your xpath to lowercase and leaving this line in, but resetting the root.InnerText seems to destroy the structure of the XML document (stepping through the code in the debugger changes the root.ChildNodes.Count
property from 2 to 1 after the above line has executed).
Your query would work if you had next XML structure:
<code>
<R>1</R>
<G>2</G>
<B>3</B>
</code>
where R,G,B are subnodes of code.
But in your case, R,G,B as well as code are subnodes of row:
<row>
<code> </code>
<R>1</R>
<G>2</G>
<B>3</B>
</row>
So query file/ROWS/row/*[not(self::code)]
will collect all R,G,B values (all subnodes of row except code).
And call doc.SelectNodes()
, not doc.DocumentElement.SelectNodes()
!
精彩评论