无法使用 XDocument 查询 XML 文档并获得所需结果
Cannot query XML document using XDocument and get desired results
我正在尝试使用 Bing 地图 API,其中 return 是一个 XML 文档。文件(简化但保持结构)是
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<StatusCode>
200
</StatusCode>
<ResourceSets>
<ResourceSet>
<Resources>
<TrafficIncident>
<Severity>
Minor
</Severity>
<RoadClosed>
false
</RoadClosed>
</TrafficIncident>
</Resources>
</ResourceSet>
</ResourceSets>
</Response>
在这种情况下,只有 1 个交通问题,但可能有很多。
我正在尝试提取道路是否封闭以及严重程度
XML 存储在 xd
对象(XDocuement
类型)
以下工作正常(没有错误,但 return 所有元素)
var allNodes = (from x in xd.Descendants()
select x).ToList();
但如果我添加一个元素名称,那么它 return 是一个包含 0 个项目的列表
var allNodes = (from x in xd.Descendants("Resources")
select x).ToList();
我认为上面的代码在说:
from xd, grab all of the descendants of the "Resources" element
如果我的理解是正确的,为什么会 return 0 个结果
您必须像这样包含您的(默认)XML 命名空间:
var name = XName.Get("Resources", "http://schemas.microsoft.com/search/local/ws/rest/v1");
var allNodes = (from x in xd.Descendants(name)
select x).ToList();
您一定不要忘记 XML 命名空间。
XNamespace search = "http://schemas.microsoft.com/search/local/ws/rest/v1";
var allNodes = (from x in xd.Descendants(search + "Resources")
select x).ToList();
我正在尝试使用 Bing 地图 API,其中 return 是一个 XML 文档。文件(简化但保持结构)是
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<StatusCode>
200
</StatusCode>
<ResourceSets>
<ResourceSet>
<Resources>
<TrafficIncident>
<Severity>
Minor
</Severity>
<RoadClosed>
false
</RoadClosed>
</TrafficIncident>
</Resources>
</ResourceSet>
</ResourceSets>
</Response>
在这种情况下,只有 1 个交通问题,但可能有很多。
我正在尝试提取道路是否封闭以及严重程度
XML 存储在 xd
对象(XDocuement
类型)
以下工作正常(没有错误,但 return 所有元素)
var allNodes = (from x in xd.Descendants()
select x).ToList();
但如果我添加一个元素名称,那么它 return 是一个包含 0 个项目的列表
var allNodes = (from x in xd.Descendants("Resources")
select x).ToList();
我认为上面的代码在说:
from xd, grab all of the descendants of the "Resources" element
如果我的理解是正确的,为什么会 return 0 个结果
您必须像这样包含您的(默认)XML 命名空间:
var name = XName.Get("Resources", "http://schemas.microsoft.com/search/local/ws/rest/v1");
var allNodes = (from x in xd.Descendants(name)
select x).ToList();
您一定不要忘记 XML 命名空间。
XNamespace search = "http://schemas.microsoft.com/search/local/ws/rest/v1";
var allNodes = (from x in xd.Descendants(search + "Resources")
select x).ToList();