XPath在C#中无法正常工作
发布时间:2020-12-15 17:36:57 所属栏目:百科 来源:网络整理
导读:我的代码不返回节点 XmlDocument xml = new XmlDocument();xml.InnerXml = text;XmlNode node_ = xml.SelectSingleNode(node);return node_.InnerText; // node_ = null ! 我很确定我的XML和Xpath是正确的. 我的Xpath:/ ItemLookupResponse / OperationRequ
我的代码不返回节点
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了! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |