tags:

views:

566

answers:

3

I am tryng to loop through an xml doc and I am still getting the first element in the second iteration, not sure what I am missing. Can anyone help? Pretty new with Xpath

string file = HttpContext.Current.Server.MapPath("~/XML/Locations.xml");

    Dictionary<string, Location> locationCollection = new Dictionary<string, Location>();

        XPathDocument xDocument = new XPathDocument(file);
        XPathNavigator xPathNavigator = xDocument.CreateNavigator();

        foreach (XPathNavigator node in xPathNavigator.Select("//locations/*"))
        {
            string value = node.SelectSingleNode("/locations/location/cell").Value;
        }



    <?xml version="1.0" encoding="utf-8" ?>
<locations>
  <location>
    <locationName>Glendale</locationName>
    <street>3717 San Fernando Road</street>
    <city>Glendale</city>
    <state>CA</state>
    <zipcode>91204</zipcode>
    <generalManager>DJ Eldon</generalManager>
    <phone>(818) 552‐6246</phone>
    <tollFree>(888) 600‐6011</tollFree>
    <fax>(818) 552‐6248</fax>
    <cell>(347) 834‐2249</cell>
    <counterEmail>[email protected]</counterEmail>
    <directEmail>[email protected]</directEmail>
  </location>
  <location>
    <locationName>Chicago</locationName>
    <street>1301 S. Harlem Ave.</street>
    <city>Chicago</city>
    <state>IL</state>
    <zipcode>60402</zipcode>
    <generalManager>Dave Schnulle</generalManager>
    <phone>(708) 749‐1500</phone>
    <tollFree>(888) 966‐1500</tollFree>
    <fax>(818) 552‐6248</fax>
    <cell>(708) 749‐3800</cell>
    <counterEmail>[email protected]</counterEmail>
    <directEmail>[email protected]</directEmail>
  </location>  
</locations>
+3  A: 

You're effectively ignoring the value of node by using a leading slash to get back to the document root. Try this instead:

// This assumes that there are only location nodes under locations;
// You may want to use //locations/location instead
foreach (XPathNavigator node in xPathNavigator.Select("//locations/*"))
{
    string value = node.SelectSingleNode("cell").Value;
    // Use value
}

Having said that, is there any reason you're not doing it in a single XPath query?

// Name changed to avoid scrolling :)
foreach (XPathNavigator node in navigator.Select("//locations/location/cell"))
{
    string value = node.Value;
    // Use value
}
Jon Skeet
Thanks, this worked great... Yes, there is a reason I am not doing a single xpath because I will be adding multipule values to a collection.Thanks again!
BoredOfBinary
A: 

Try the following:

XPathNodeIterator ni = xPathNavigator.Select("//locations/*");
while (ni.MoveNext())
{
    string value = ni.Current.Value);
}

Just a quick blurt, hope it helps you.

Onots
A: 

you should do:

string value = node.SelectSingleNode("./cell").Value;

When you do xPathNavigator.Select("//locations/*")), you're already inside /locations/location so you need to move just one element down the node, cell in your example.

jeremy