简体   繁体   English

如何使用XDocument获取值

[英]How to grab value using XDocument

I have this xml from which I am trying to grab the value in the node <ErrorCode> after investigating, i found it easier to use XDocument because it cleans any unwanted \\r\\n that the response from an api was giving me.. but now I am not sure how to retrieve that value using XDocument 我有这个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>

I want to be able to take advantage of this call to get the value 我希望能够利用这个调用获得价值

 XDocument xmlResponse = XDocument.Parse(response);

I can't use XmlDocument because it does not clean the XML as it is doing it XDocument 我不能使用XmlDocument,因为它不会清理XML,因为它正在执行XDocument

Thank you 谢谢

Since you have defined the Namespace, try the following code: 由于您已定义了命名空间,请尝试以下代码:

    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;

Or if you don't want to use Namespace then: 或者如果您不想使用Namespace,那么:

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

you can use xpath structure to get the value somethink like this 你可以使用xpath结构来获得像这样的值

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

or this 或这个

string result = xmlResponse.Descendants("ErrorCode").Single().Value;
XDocument doc = XDocument.Load("YouXMLPath");

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM