Reputation: 409
I have this XML that I am parsing and for some reason when I try to pull out the "routes" values, I am only getting the first one in the list. So basically I can extract the "1" value but the rest are being skipped/ignored. I think it's something to do with the nested elements being so far "down" the list but I'm not sure what the problem is.
Any ideas how I can pull out all the route values and not just the first one in the list?
<information xmlns="http://testnamespace" xmlns:i="http://www.w3.org/2001/XMLSchema- instance">
<errorcode>0</errorcode>
<errormessage/>
<numberofresults>1</numberofresults>
<timestamp>12/01/2014 17:20:04</timestamp>
<results>
<result>
<id>1234</id>
<displayid>1234</displayid>
<name>A Road</name>
<name2>Another Road</name2>
<element1>
<element2>
<name>abc</name>
<routes>
<route>1</route>
<route>2</route>
<route>3</route>
<route>4</route>
<route>5</route>
<route>6</route>
</routes>
</element2>
</element1>
</result>
</results>
</information>
This is my code:
foreach (var routeInfo in StopInfo.Descendants(ns + "routes"))
{
string route = routeInfo.Element(ns + "route").Value;
lstResults.Items.Add(route);
}
Upvotes: 1
Views: 123
Reputation: 294
Although Sergey Berezovskiy has already provided solution but rather we can also use XMLSerializer and annotation for parsing xml in windows phone For reference http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.100).aspx
This might increse number of classes but this is the best way to parse XML data in Windows Phone
Upvotes: 0
Reputation: 236278
You are getting only single route element of routes
(and it will be first element with value 1
):
routeInfo.Element(ns + "route")
And you do same thing for each routes
element in you xml. So, if you have only one routes
element in your xml, you'll end with single value 1
added to listbox. What you need is getting route
elements of selected routes
element (they are direct children, so simple Elements()
will do the job):
foreach (var route in StopInfo.Descendants(ns + "routes").Elements())
lstResults.Items.Add((string)route);
Also keep in mind that you can simply cast XElement
to string and some other types to get their value. That will allow to avoid exception if element is not found and you are trying to read its value.
Upvotes: 2
Reputation: 125650
Because you need more then one route
element you should use another loop:
foreach (var routeInfo in StopInfo.Descendants(ns + "routes"))
{
foreach(var route = routeInfo.Elements(ns + "route"))
lstResults.Items.Add((string)route);
}
Upvotes: 0