【问题标题】:How to use XElement.Parse and then find the value of a specific element?如何使用 XElement.Parse 然后找到特定元素的值?
【发布时间】:2012-11-07 21:43:41
【问题描述】:

我有一些从 REST 调用返回的 XML,如下所示:

<ArrayOfProperty xmlns=\"http://schemas.microsoft.com/HPCS2008R2/common\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
  <Property>
    <Name>Id</Name>
    <Value>17</Value>
  </Property>
  <Property>
    <Name>StartTime</Name>
    <Value>11/7/2012 9:13:50 PM</Value>
  </Property>
  <Property>
    <Name>State</Name>
    <Value>Failed</Value>
  </Property>

我正在使用 RestSharp API 来协助执行 API 调用并尝试使用 linq-to-xml XElement.Parse 来解析结果。我不确定如何获取状态的值,以便从本文档中我想做类似的事情:

XElement.Parse(XMLstring).Elements??? 从包含元素 State 的元素集中获取文本“失败”,但我想要来自 &lt;Value&gt;Failed&lt;/Value&gt; 元素的文本“失败”。该值元素可以有多个值,但我总是想要与状态关联的值。

有什么想法吗?

【问题讨论】:

    标签: c# .net xml linq linq-to-xml


    【解决方案1】:

    您的 XML 包含默认命名空间,因此您需要定义它并在查询中使用。

    XNamespace ns = "http://schemas.microsoft.com/HPCS2008R2/common";
    
    var value = (string)XDocument.Parse(input)
        .Descendants(ns + "Property")
        .Where(p => (string)p.Element(ns + "Name") == "State")
        .Elements(ns + "Value").FirstOrDefault();
    

    【讨论】:

    • 太棒了!非常感谢;我一直在为此绞尽脑汁。
    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多