我目前有以下代码
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(为了可读性而截断)
<?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(&#34; // soapenv:Envelope / soapenv:Body / message&#34;,nsmgr);当我希望它返回消息元素时返回null。
我非常怀疑它与我配置的空白命名空间有关,但我找不到合适的值组合以使其正常工作。
任何指针都会受到赞赏。
答案 0 :(得分:1)
您已在此处介绍默认命名空间:
xmlns="http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractDetailResponse"
导致message
元素及其所有没有前缀的后代被识别为在该默认命名空间中(除非后代元素具有本地默认命名空间)。要访问默认命名空间中的元素,只需注册一个前缀,例如d
,并将其映射到默认命名空间uri:
nsmgr.AddNamespace("d", "http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractDetailResponse");
然后在XPath表达式中相应地使用新注册的前缀:
XmlNode xnBody = xmlDoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body", nsmgr);
XmlNode xnMessage = xnBody.SelectSingleNode("d:message", nsmgr);
答案 1 :(得分:1)
这是有效的
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\Users\DummyUser\Desktop\Noname1.xml");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("de", "http://www.origostandards.com/schema/ce/v2.1/CEBondSingleContractDetailResponse");
XmlNode xnEnvelope = xmlDoc.SelectSingleNode("//soapenv:Envelope", nsmgr);
XmlNode xnBody = xnEnvelope.SelectSingleNode("//soapenv:Body", nsmgr);
XmlNode xnMessage = xnBody.SelectSingleNode("de:message", nsmgr);
和xml文件是
<?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">
This is my sample message
</message>
</soapenv:Body>
</soapenv:Envelope>