XPath遇到Namespace的时候取值比较麻烦,需要通过XmlNamespaceManager来添加ns context支持
我一般也是用这种方法来处理Namespace,但是有时需要动态生成XPath,所以我有时会采用以下的方法
//*[local-name()='Header' and namespace-uri()='http://www.monternet.com/dsmp/schemas/']
//*[local-name()='Header']/*[local-name()='TransactionID']
以下摘自阿良.NET
嘻嘻,应阿良的要求,引用自博客园谭振林
--------------------------------------------
<?xml version="1.0" encoding="utf-8"?> <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Header> <TransactionID xmlns="http://www.monternet.com/dsmp/schemas/">06070516230084</TransactionID> </SOAP-ENV:Header> <SOAP-ENV:Body> <SyncOrderRelationReq xmlns="http://www.monternet.com/dsmp/schemas/"> <Version>1.5.0</Version> <MsgType>SyncOrderRelationReq</MsgType> <Send_Address> <DeviceType>0</DeviceType> <DeviceID>0011</DeviceID> </Send_Address> <Dest_Address> <DeviceType>400</DeviceType> <DeviceID>0</DeviceID> </Dest_Address> <FeeUser_ID> <UserIDType>1</UserIDType> <MSISDN>13800138000</MSISDN> <PseudoCode> </PseudoCode> </FeeUser_ID> <DestUser_ID> <UserIDType>1</UserIDType> <MSISDN>13800138000</MSISDN> <PseudoCode></PseudoCode> </DestUser_ID> <LinkID>LinkID</LinkID> <ActionID>1</ActionID> <ActionReasonID>1</ActionReasonID> <SPID>900000</SPID> <SPServiceID>abcd</SPServiceID> <AccessMode>3</AccessMode> <FeatureStr></FeatureStr> </SyncOrderRelationReq> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
string xml = ""; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); xmlDoc.SelectNodes("//SOAP-ENV:Header/TransationID");//取不到任何节点
此时,需要对命名空间一一定义:
string xml = ""; XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(xml); XmlNamespaceManager xnm = new XmlNamespaceManager(xmldoc.NameTable); xnm.AddNamespace("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); xnm.AddNamespace("Mo", "http://www.monternet.com/dsmp/schemas/"); //注意,就算是用默认命名空间的节点,也要为命名空间定义一个名字,并使用这个名字。 xmldoc.SelectNodes("//SOAP-ENV:Header/Mo:TransationID", xnm);
---------------------------------------------
以上摘自阿良.NET