XmlDocument.SelectSingleNode

时间:2015-03-05 05:07:23

标签: c# asp.net xml

我有一条soap xml消息,需要从给定的soap xml

中获取单个节点值
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://tews6/wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.xmlsoap.org/soap/envelope/ http://schemas.xmlsoap.org/soap/envelope/" >
<soapenv:Body>
<testResult>
<Status version="6.0" >
<NNO>277982b4-2917a65f-13ffb8c0-b09751f</NNO>
</Status>
<ProfileTab>
<Email>abc@gmail.com</Email>
<Name>abc</Name>
</Profile>
</testResult></soapenv:Body></soapenv:Envelope>

我需要获取Email节点的值。我使用下面的代码

 rootNode = "soapenv:Envelope/soapenv:Body/ProfileTab/Email";

 var nsmgr = new XmlNamespaceManager(document.NameTable);
 nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
 nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");

 node = document.SelectSingleNode(rootNode,nsmgr);

返回null。

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容。

var rootNode = "soapenv:Envelope/soapenv:Body/tews6:testResult/tews6:ProfileTab/tews6:Email";

var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("tews6", "http://tews6/wsdl");
nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");

var node = doc.SelectSingleNode(rootNode, nsmgr);

答案 1 :(得分:0)

试试这个:

string xml="xml"; 
XDocument doc = XDocument.Parse(xml);
 XNamespace bodyNameSpace ="http://schemas.xmlsoap.org/soap/envelope/";
 var bodyXml = from _e in doc.Descendants(bodyNameSpace + "Body")
                          select _e;
 if (bodyXml.Elements().Count() == 0)
            {
                return;
            }
var email = from _e in bodyXml.First()Descendants("Email")
                                      select _e;
if(email.Count()==1)
{
    string emailAddress=email.First().Value;
}