2012-03-13 56 views
2

我正在0计数结果时,我使用XDcoument对象转换XML到字符串数组,字符串数组按照下面问题与XML文档转换为字符串数组

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> 

代码获取位置名称的数组应该是什么问题?

回答

1

一个有趣的问题,这是一个计数。

由于您的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; 
+0

感谢两个查询担任魅力! – 2012-03-13 09:13:09

+0

欢迎您! :) – gideon 2012-03-13 09:17:32

1

您在位置元素中有一个名称空间定义。所以元素的名称是{http://schemas.microsoft.com/windowsazure}Location而不是位置。

如果您从该位置元素命名空间定义,然后将您的查询正确执行并返回9个位置元素