XPath在C#中无法正常工作

前端之家收集整理的这篇文章主要介绍了XPath在C#中无法正常工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的代码不返回节点
  1. XmlDocument xml = new XmlDocument();
  2. xml.InnerXml = text;
  3.  
  4. XmlNode node_ = xml.SelectSingleNode(node);
  5. return node_.InnerText; // node_ = null !

我很确定我的XML和Xpath是正确的.

我的Xpath:/ ItemLookupResponse / OperationRequest / RequestId

我的XML:

  1. <?xml version="1.0"?>
  2. <ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
  3. <OperationRequest>
  4. <RequestId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx</RequestId>
  5. <!-- the rest of the xml is irrelevant -->
  6. </OperationRequest>
  7. </ItemLookupResponse>

由于某些原因,我的XPath返回的节点总是为空.有人可以帮忙吗?

解决方法

您的XPath几乎是正确的 – 它根本不考虑根节点上的默认XML命名空间!
  1. <ItemLookupResponse
  2. xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
  3. *** you need to respect this namespace ***

您需要考虑到这一点,并更改您的代码

  1. XmlDocument xml = new XmlDocument();
  2. xml.InnerXml = text;
  3.  
  4. XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NaMetable);
  5. nsmgr.AddNamespace("x","http://webservices.amazon.com/AWSECommerceService/2005-10-05");
  6.  
  7. XmlNode node_ = xml.SelectSingleNode(node,nsmgr);

然后你的XPath应该是:

  1. /x:ItemLookupResponse/x:OperationRequest/x:RequestId

现在,你的node_.InnerText绝对不会是NULL了!

猜你在找的C#相关文章