C# Can';t分析嵌套元素
我正在解析这个XML,出于某种原因,当我尝试提取“routes”值时,我只得到列表中的第一个值。因此,基本上我可以提取“1”值,但其余值被跳过/忽略。我认为这与嵌套元素在列表中的位置“向下”有关,但我不确定问题出在哪里 你知道我如何提取所有路线值,而不仅仅是列表中的第一个吗C# Can';t分析嵌套元素,c#,xml,windows-phone-8,linq-to-xml,C#,Xml,Windows Phone 8,Linq To Xml,我正在解析这个XML,出于某种原因,当我尝试提取“routes”值时,我只得到列表中的第一个值。因此,基本上我可以提取“1”值,但其余值被跳过/忽略。我认为这与嵌套元素在列表中的位置“向下”有关,但我不确定问题出在哪里 你知道我如何提取所有路线值,而不仅仅是列表中的第一个吗 <information xmlns="http://testnamespace" xmlns:i="http://www.w3.org/2001/XMLSchema- instance"> <e
<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>
您只获得
路由的单个路由元素(它将是第一个值为1
)的元素:
对xml中的每个元素执行相同的操作。因此,如果xml中只有一个routes
元素,则会在列表框中添加一个值1
。您需要的是获取所选route
元素的routes
元素(它们是直接子元素,因此简单的elements()
就可以完成这项工作):
还请记住,您可以简单地将XElement
强制转换为string和其他一些类型以获得它们的值。如果未找到元素且您试图读取其值,则可以避免异常。因为您需要不止一个路由
元素,所以应该使用另一个循环:
foreach (var routeInfo in StopInfo.Descendants(ns + "routes"))
{
foreach(var route = routeInfo.Elements(ns + "route"))
lstResults.Items.Add((string)route);
}
虽然Sergey Berezovskiy已经提供了解决方案,但我们也可以使用XMLSerializer和注释在windows phone中解析xml以供参考
这可能会增加类的数量,但这是在Windows Phone中解析XML数据的最佳方法谢谢,这很有效。但是有没有一种方法可以分别提取每个值呢?当我将它们添加到列表框中时,它只是将123456作为一个字符串添加,而不是在它自己的行中添加每个字符串。@irldev上面的代码应该将六个路由项添加到列表框中。你只想要前四个?对不起,是的,我想要全部6个项目。我试过你最近的编辑,效果不错,谢谢!
routeInfo.Element(ns + "route")
foreach (var route in StopInfo.Descendants(ns + "routes").Elements())
lstResults.Items.Add((string)route);
foreach (var routeInfo in StopInfo.Descendants(ns + "routes"))
{
foreach(var route = routeInfo.Elements(ns + "route"))
lstResults.Items.Add((string)route);
}