如何使用XDocument获取值

use*_*156 4 c# asp.net linq-to-xml

我有这个xml,我试图<ErrorCode>在调查后尝试获取节点中的值,我发现使用XDocument更容易,因为它清除了任何不需要\r\n的来自api的响应给了我..但是现在我不知道如何使用XDocument检索该值

<PlatformResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://platform.intuit.com/api/v1">
  <ErrorMessage>OAuth Token rejected</ErrorMessage>
  <ErrorCode>270</ErrorCode>
  <ServerTime>2012-06-19T03:53:34.4558857Z</ServerTime>
</PlatformResponse>
Run Code Online (Sandbox Code Playgroud)

我希望能够利用这个调用获得价值

 XDocument xmlResponse = XDocument.Parse(response);
Run Code Online (Sandbox Code Playgroud)

我不能使用XmlDocument,因为它不会清理XML,因为它正在执行XDocument

谢谢

Hab*_*bib 10

由于您已定义了命名空间,请尝试以下代码:

    XDocument xmlResponse = XDocument.Load("yourfile.xml");
    //Or you can use XDocument xmlResponse = XDocument.Parse(response)
    XNamespace ns= "http://platform.intuit.com/api/v1";
    var test = xmlResponse.Descendants(ns+ "ErrorCode").FirstOrDefault().Value;
Run Code Online (Sandbox Code Playgroud)

或者如果您不想使用Namespace,那么:

    var test3 = xmlResponse.Descendants()
                .Where(a => a.Name.LocalName == "ErrorCode")
                .FirstOrDefault().Value;
Run Code Online (Sandbox Code Playgroud)