2

所以,这可能是一个非常愚蠢的问题,但我很难找到一个真正有效的答案。

所以我得到了一个看起来像这样的xml。

<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>

我只需要检索停止位置,然后检索每个位置的不同信息。

XDocument xdoc = XDocument.Parse(e.Result);
foreach (var busstop in xdoc.Descendants())
{
     //return the whole node here       
}

如何从每个停靠点提取名称、x、y 和 id、距离值?:)

4

1 回答 1

5

如何从每个停靠点提取名称、x、y 和 id、距离值?

非常简单 - 只需转换属性:

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
}

如果你真的要创建一个新对象,你应该考虑使用Select,以声明方式完成整个事情。例如:

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()

当然,这是假设有一个构造函数BusStop按顺序获取这些值。

于 2013-05-24T01:35:29.733 回答