【问题标题】:WP7 Linq to XML to get a child element of an XElement by nameWP7 Linq to XML 通过名称获取 XElement 的子元素
【发布时间】:2010-12-11 09:21:11
【问题描述】:

我知道这是一个有点简单的问题,但即使在查看了 SO 和 LINQ to XML 教程的答案之后,我也无法让它发挥作用。我使用的是 Windows Phone 7,但我认为这不会有什么不同。

我的 XML 看起来像这样:

<response xmlns="http://anamespace.com/stuff/">
    <error code="ERROR_CODE_1">You have a type 1 error</error>
</response>

我将上面的 XML 加载到 XElement 中。我想获得“错误”节点。 This question 表示您需要处理命名空间。我已经尝试过使用和不使用命名空间的查询,但无论哪种方式都不起作用。

使用命名空间查询:

private object ParseElement(XElement responseElement)
{
    XNamespace ns = "http://anamespace.com/stuff/";
    IEnumerable<XElement> errorNodes = from e in responseElement.Elements(ns + "error") select e;
}

没有命名空间的查询:

private object ParseElement(XElement responseElement)
{
    IEnumerable<XElement> errorNodes = from e in responseElement.Elements("error") select e;
}

errorNodes 变量永远不会被 XElements 填充。我读过的教程都使用这种表示法来按名称选择元素,但它对我不起作用。

【问题讨论】:

    标签: c# .net silverlight windows-phone-7 linq-to-xml


    【解决方案1】:

    此代码在我的机器上工作™:

    XElement response = XElement.Parse(
    @"<response xmlns=""http://anamespace.com/stuff/"">
        <error code=""ERROR_CODE_1"">You have a type 1 error</error>
    </response>");
    
    XNamespace ns = "http://anamespace.com/stuff/";
    
    XElement error = response.Element(ns + "error");
    
    string code = (string)error.Attribute("code");
    string message = (string)error;
    
    Console.WriteLine(code);
    Console.WriteLine(message);
    

    我的机器运行的是常规的 .NET 4,所以也许你可以运行这段代码并检查它是否适用于 WP7。

    【讨论】:

      【解决方案2】:

      您是否有机会阅读整个文档而不是 error 元素?

      如果你使用Descendants而不是Elements,它会起作用吗?

      [TestMethod]
      public void CanGetErrorElements()
      {
          string xml = @"
      <response xmlns=""http://anamespace.com/stuff"">
      <error code=""ERROR_CODE_1"">You have a type 1 error</error>
      </response>";
          XDocument doc = XDocument.Parse(xml);
          XNamespace ns = "http://anamespace.com/stuff";
          var errorNodes = from e in doc.Descendants(ns + "error") 
                           select e;
          Assert.IsTrue(errorNodes.Count() > 0);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多