Here is an example XML doc that matches the one I am getting info from:
<?xml version="1.0" standalone="yes"?>
<Products xmlns="http://tempuri.org/Products.xsd">
<Movies>
<Title>Title1</Title>
<Language>English</Language>
</Movies>
<Movies>
<Title>Title2</Title>
<Language>English</Language>
</Movies>
<Movies>
<Title>Title3</Title>
<Language>French</Language>
</Movies>
<Books>
<Title>BTitle1</Title>
<Genre>Suspense</Genre>
</Books>
<Books>
<Title>BTitle2</Title>
<Genre>Suspense</Genre>
</Books>
<Books>
<Title>BTitle3</Title>
<Genre>SciFi</Genre>
</Books>
<Books>
<Title>BTitle4</Title>
<Genre>SciFi</Genre>
</Books>
</Products>
Here is my code to get all books with the genre of Suspense:
//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
string booksQuery = "Books[Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery);
while (xIter.MoveNext())
{
//do stuff with xIter.Current
}
I have tried several queries including Products/Books[Genre = \"Suspense\"]
, Products/Books
, ./Books
, and Books
. My xIter always has zero items.
I'm new to XPath, so I'm sure it's a really simple error, but maybe not. I know I can get a DataSet with the tables [Movies] and [Books] out of this XML file using myDataSet.ReadXml(myXmlPathString);
so the XML file is not corrupt. If that helps any.
So, my question ... what am I doing wrong?
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
XmlNamespaceManager mngr = new XmlNamespaceManager(xNav.NameTable);
mngr.AddNamespace("p", "http://tempuri.org/Products.xsd");
string booksQuery = "//p:Books[p:Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery,mngr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With