Kri*_*oks 10 c# xml xpath xml-namespaces
我的代码没有返回节点
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNode node_ = xml.SelectSingleNode(node);
return node_.InnerText; // node_ = null !
Run Code Online (Sandbox Code Playgroud)
我很确定我的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>
Run Code Online (Sandbox Code Playgroud)
由于某种原因,我的XPath返回的节点始终为null.有人可以帮忙吗?
mar*_*c_s 20
你的XPath几乎是正确的 - 它没有考虑根节点上的默认XML命名空间!
<ItemLookupResponse
xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
*** you need to respect this namespace ***
Run Code Online (Sandbox Code Playgroud)
您需要考虑到这一点并更改您的代码,如下所示:
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);
Run Code Online (Sandbox Code Playgroud)
然后你的XPath应该是:
/x:ItemLookupResponse/x:OperationRequest/x:RequestId
Run Code Online (Sandbox Code Playgroud)
现在,你的node_.InnerText绝对不应该是NULL!