Reputation: 4801
So, this might be a really stupid question, but I'm having a hard to finding an answer that actually works.
So I got an xml looking like this.
<LocationList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlopen.rejseplanen.dk/xml/rest/hafasRestStopsNearby.xsd">
<StopLocation name="Tesdorpfsvej (Odense Kommune)" x="10400699" y="55388303" id="461769300" distance="205"/>
<StopLocation name="Tesdorpfsvej / Munkebjergvej (Odense Kommune)" x="10400681" y="55388303" id="461055900" distance="206"/>
<StopLocation name="Munkebjerg Plads (Odense Kommune)" x="10401589" y="55386873" id="461120400" distance="312"/>
<StopLocation name="Munkebjergvej (Odense Kommune)" x="10397463" y="55390514" id="461038500" distance="372"/>
<StopLocation name="Jagtvej (Odense Kommune)" x="10396456" y="55389489" id="461019400" distance="420"/>
<StopLocation name="Allegade (Odense Kommune)" x="10396618" y="55390721" id="461026900" distance="430"/>
<StopLocation name="Guldbergsvej (Odense Kommune)" x="10396923" y="55391422" id="461104100" distance="443"/>
<StopLocation name="Nansensgade (Odense Kommune)" x="10409436" y="55391799" id="461115400" distance="472"/>
<StopLocation name="Chr. Sonnes Vej (Odense Kommune)" x="10404483" y="55385219" id="461120300" distance="488"/>
<StopLocation name="Benedikts Plads (Odense Kommune)" x="10398254" y="55392995" id="461115500" distance="491"/>
</LocationList>
I only need to retrieve the stoplocation, and then the different info in each of them.
XDocument xdoc = XDocument.Parse(e.Result);
foreach (var busstop in xdoc.Descendants())
{
//return the whole node here
}
How can I extract the name, x, y and id, distance value from each stop location? :)
Upvotes: 2
Views: 975
Reputation: 1501163
How can I extract the name, x, y and id, distance value from each stop location?
Very simply - just cast the attributes:
XDocument xdoc = XDocument.Parse(e.Result);
foreach (var stop in xdoc.Root.Elements("StopLocation"))
{
int x = (int) stop.Attribute("x");
int y = (int) stop.Attribute("y");
int id = (int) stop.Attribute("id");
int distance = (int) stop.Attribute("distance");
// Use the variables here
}
If you're actually going to create a new object, you should consider using Select
instead, to do the whole thing declaratively. For example:
XDocument xdoc = XDocument.Parse(e.Result);
var stops = xdoc.Root
.Elements("StopLocation")
.Select(stop => new BusStop(
(int) stop.Attribute("x"),
(int) stop.Attribute("y"),
(int) stop.Attribute("id"),
(int) stop.Attribute("distance")))
.ToList()
That's assuming there's a constructor for BusStop
that takes those values in that order, of course.
Upvotes: 5