根据需要在C#中的XPath不工作 [英] XPath doesn't work as desired in C#
本文介绍了根据需要在C#中的XPath不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码不会返回节点
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNode node_ = xml.SelectSingleNode(node);
return node_.InnerText; // node_ = null !
我敢肯定我的XML和XPath是正确的。
I'm pretty sure my XML and Xpath are correct.
我的Xpath: / ItemLookupResponse / OperationRequest /请求ID
我的XML:
<?xml version="1.0"?>
<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
<OperationRequest>
<RequestId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx</RequestId>
<!-- the rest of the xml is irrelevant -->
</OperationRequest>
</ItemLookupResponse>
节点我的XPath返回总是空的某些原因。 ?谁能帮
The node my XPath returns is always null for some reason. Can someone help?
推荐答案
您的XPath几乎是正确的 - 它只是没有考虑到根目录下的默认XML命名空间!节点
Your XPath is almost correct - it just doesn't take into account the default XML namespace on the root node!
<ItemLookupResponse
xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
*** you need to respect this namespace ***
您需要采取考虑并改变你这样的代码:
You need to take that into account and change your code like this:
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("x", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
XmlNode node_ = xml.SelectSingleNode(node, nsmgr);
和那么你的XPath应该是:
And then your XPath ought to be:
/x:ItemLookupResponse/x:OperationRequest/x:RequestId
现在,您node_.InnerText绝对应该的不的是NULL了!
Now, your node_.InnerText should definitely not be NULL anymore!
这篇关于根据需要在C#中的XPath不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文