【问题标题】:Issue with converting XML document to string array将 XML 文档转换为字符串数组的问题
【发布时间】:2012-03-13 08:35:42
【问题描述】:

当我使用 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>

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

【问题讨论】:

    标签: linq c#-4.0 linq-to-xml


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

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

      如果您从 Locations 元素中删除命名空间定义,那么您的查询将正确执行并返回 9 个 Location 元素的计数

      【讨论】:

        猜你喜欢
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 2014-04-05
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 2017-12-02
        • 2013-05-30
        相关资源
        最近更新 更多