XPath在C#中无法正常工作

我的代码没有返回节点

XmlDocument xml = new XmlDocument(); xml.InnerXml = text; XmlNode node_ = xml.SelectSingleNode(node); return node_.InnerText; // node_ = null ! 

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

我的Xpath: /ItemLookupResponse/OperationRequest/RequestId

我的XML:

    xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx    

由于某种原因,我的XPath返回的节点始终为null。 有人可以帮忙吗?

您的XPath几乎是正确的 – 它只是没有考虑根节点上的默认XML命名空间!

  *** 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!

很抱歉迟到的回复,但刚才我遇到了类似的问题。

如果您真的想忽略该命名空间,那么只需从用于初始化XmlDocument的字符串中删除它

 text=text.Replace( "", ""); XmlDocument xml = new XmlDocument(); xml.InnerXml = text; XmlNode node_ = xml.SelectSingleNode(node); return node_.InnerText;