简体   繁体   English

C#从XML响应获取值

[英]c# get values from xml response

I am trying to get values from xml respone : 我试图从xml respone获取值:

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://adaddaasd.com">
<A>14</A>
<B>Failed</B>
<C>22</C>
</Response>

My code is : 我的代码是:

string responseString = await response.Content.ReadAsStringAsync();

var xDocument = XDocument.Parse(responseString);

var responseNode = xDocument.XPathSelectElement("/Response");
var A = xDocument.XPathSelectElement("/Response/A");

But I am getting null values for A and responseNode. 但是我得到A和responseNode的空值。 Whats wrong? 怎么了? Thanks 谢谢

You're blatantly ignoring the XML namespace that's defined in your XML document: 公然忽略了XML文档中定义的XML名称空间:

<Response xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
          xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
          xmlns='http://adaddaasd.com'>
          ****************************

You need to include that into your querying - I would try to do it like this: 您需要将其包括在查询中-我将尝试这样做:

var xDocument = XDocument.Parse(responseString);

// *define* your XML namespace!
XNamespace ns = "http://adaddaasd.com";

// get all the <Response> nodes under the root with that XML namespace
var responseNode = xDocument.Descendants(ns + "Response");

// from the first <Response> node - get the descendant <A> nodes
var A = responseNode.FirstOrDefault()?.Descendants(ns + "A");

If you insist on using the XPathSelectElement method, then you must define an XmlNamespaceManager and use it in your XPath select: 如果您坚持使用XPathSelectElement方法,那么必须定义一个XmlNamespaceManager并在您的XPath选择中使用它:

// define your XML namespaces
XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(new NameTable());
xmlnsmgr.AddNamespace("ns", "http://adaddaasd.com");

// use the defined XML namespace prefix in your XPath select
var A = xDocument.XPathSelectElement("/ns:Response/ns:A", xmlnsmgr);

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

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