通过有效的 xpath 在 XmlDocument.SelectSingleNode 上返回空值 [英] Null return on XmlDocument.SelectSingleNode through valid xpath
问题描述
我目前有以下代码
nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("soapenv", soapenv_namespace);
nsmgr.AddNamespace("de", de_namespace);
XmlNode xnEnvelope = xmlDoc.SelectSingleNode("//soapenv:Envelope", nsmgr);
XmlNode xnBody = xmlDoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body", nsmgr);
XmlNode xnMessage = xnBody.SelectSingleNode("//soapenv:Envelope/soapenv:Body/message", nsmgr);
解析以下 xml(为了便于阅读而被截断)
Which parses the following xml (truncated for readibility)
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<message xmlns="http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractDetailResponse" xmlns:ns2="http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractReferenceResponse" xmlns:ns3="http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractRequest" xmlns:ns4="http://www.origostandards.com/schema/tech/v1.0/SOAPFaultDetail">
<de:m_content .....
问题是线路XmlNode xnMessage = xnBody.SelectSingleNode("//soapenv:Envelope/soapenv:Body/message", nsmgr);当我希望它返回消息元素时返回 null.
Problem is the line XmlNode xnMessage = xnBody.SelectSingleNode("//soapenv:Envelope/soapenv:Body/message", nsmgr); returns null when i'd expect it to return the message element.
我高度怀疑它与我配置的空白命名空间有关,但我找不到正确的值组合来使其正常工作.
I highly suspect its to do with the blank namespace I have configured but I cant find the right combination of values to get it working.
任何指针将不胜感激.
推荐答案
您在此处引入了默认命名空间 :
xmlns="http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractDetailResponse"
这导致 message
元素及其所有没有前缀的后代被识别为该默认命名空间(除非后代元素具有本地默认命名空间).要访问默认命名空间中的元素,只需注册一个前缀,例如 d
,并将其映射到默认命名空间 uri :
which causes message
element and all of it's descendants without prefix to be recognized as in that default namespace (unless the descendant element has local default namespace). To access element in default namespace, simply register a prefix, for example d
, and map it to the default namespace uri :
nsmgr.AddNamespace("d", "http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractDetailResponse");
然后在 XPath 表达式中相应地使用新注册的前缀:
Then use the newly registered prefix accordingly in the XPath expression :
XmlNode xnBody = xmlDoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body", nsmgr);
XmlNode xnMessage = xnBody.SelectSingleNode("d:message", nsmgr);
这篇关于通过有效的 xpath 在 XmlDocument.SelectSingleNode 上返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!