Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XPath help - Expression not working

Tags:

c#

xml

xpath

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?

like image 474
Mike Webb Avatar asked Jan 18 '11 19:01

Mike Webb


1 Answers

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);
like image 144
theChrisKent Avatar answered Sep 21 '22 01:09

theChrisKent