我的代码不返回节点
XmlDocument xml = new XmlDocument(); xml.InnerXml = text; XmlNode node_ = xml.SelectSingleNode(node); return node_.InnerText; // node_ = null !
我很确定我的XML和Xpath是正确的.
我的Xpath:/ ItemLookupResponse / OperationRequest / RequestId
我的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返回的节点总是为空.有人可以帮忙吗?
解决方法
您的XPath几乎是正确的 – 它根本不考虑根节点上的默认XML命名空间!
<ItemLookupResponse
xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
*** you need to respect this namespace ***
您需要考虑到这一点,并更改您的代码:
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应该是:
/x:ItemLookupResponse/x:OperationRequest/x:RequestId
现在,你的node_.InnerText绝对不会是NULL了!