当我使用 XDcoument 对象将 XML 转换为字符串数组时,我得到 0 计数结果,如下所示
Stream dataStream = response.GetResponseStream();
XDocument doc = XDocument.Load((dataStream));
var services = from s in doc.Descendants("Location")
select (string)s.Element("Name");
string[] locationArray = services.ToArray();
文档如下
<Locations xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Location>
<Name>Anywhere US</Name>
</Location>
<Location>
<Name>South Central US</Name>
</Location>
<Location>
<Name>Anywhere Europe</Name>
</Location>
<Location>
<Name>West Europe</Name>
</Location>
<Location>
<Name>Anywhere Asia</Name>
</Location>
<Location>
<Name>Southeast Asia</Name>
</Location>
<Location>
<Name>East Asia</Name>
</Location>
<Location>
<Name>North Central US</Name>
</Location>
<Location>
<Name>North Europe</Name>
</Location>
</Locations>
获取位置名称数组的代码应该有什么问题?
最佳答案
这是一个有趣的问题。
由于您的 xmlns
命名空间,元素名称都具有该命名空间。这有效:
var locations = from s in
doc.Descendants("{http://schemas.microsoft.com/windowsazure}Name")
select s.Value;
locations
现在包含您的所有位置
为了使其更具可读性,您可以这样做:
var services = from s in doc.Descendants()
where s.Name.LocalName == "Location"
select s.Value;
关于linq - 将 XML 文档转换为字符串数组时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9680622/