如何使用XDocument获取值

4

我有一个XML文件,想要获取节点<ErrorCode>中的值。经过调查后,我发现使用XDocument更容易,因为它可以清除API响应中任何不需要的\r\n。但是现在我不确定如何使用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>

我希望能够利用这个调用来获取值。

 XDocument xmlResponse = XDocument.Parse(response);

我不能使用XmlDocument,因为它不会像XDocument一样清理XML。

谢谢。

3个回答

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;

或者如果你不想使用命名空间:

    var test3 = xmlResponse.Descendants()
                .Where(a => a.Name.LocalName == "ErrorCode")
                .FirstOrDefault().Value;

1
+1 但我会使用 (string)xmlResponse.Descendants(ns+ "ErrorCode").FirstOrDefault(); 如果错误代码不存在,则返回 null。 - AnthonyWJones

0

你可以使用XPath结构来获取值,类似于这样的操作

string errorcode= xmlResponse.SelectSingleNode("PlatformResponse/ErrorCode").InnerText

或者这个

string result = xmlResponse.Descendants("ErrorCode").Single().Value;

我不想使用XmlDocument,我需要使用XDocument,因为它可以解析并清除API返回的额外\r\n。 - user1416156
无论你如何命名变量,它都应该正常工作。 - COLD TOLD

0
XDocument doc = XDocument.Load("YouXMLPath");

var query = from d in doc.Root.Descendants()
            where d.Name.LocalName == "ErrorCode"
            select d.Value;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接