我需要解析在调用SOAP Web服务时返回的XML响应。如果我将普通的XML字符串或文档传递给xDocument.Load()
方法,则以下代码有效,但在传入响应XML时不起作用。
public static HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http:localhost:15233/myservice.asmx");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
public void execute()
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?xml version='1.0' encoding='utf-8'?>
<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
<soap:Body>
<Member xmlns='http://tempuri.org/'>
<memdid>123</memid>
<membername>Michael</membername>
<location>Somewhere</location>
</Member>
</soap:Body>
</soap:Envelope>");
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
//Get the Response
HttpWebResponse wr = (HttpWebResponse)request.GetResponse();
StreamReader rd = new StreamReader(wr.GetResponseStream());
//The response to parse
string xmlresponse = rd.ReadToEnd();
StringReader sr = new StringReader(xmlresponse);
XDocument doc = XDocument.Load(sr);
//Response.Write(doc);
var items = from p in doc.Descendants("MemResponse")
select new
{
Phone = p.Element("Phone").Value,
Email = p.Element("Email").Value
};
foreach (var re in items)
{
Response.Write(re.Phone);
}
}
返回的xml响应具有以下格式:
<?xml version="1.0" encoding="UTF-8"?>
<MemResponse>
<Phone>2554535</Phone>
<Email>mail@mail</Email>
<UniqueNumber>we75546654</UniqueNumber>
</MemResponse>
并且响应在代码中表示为:string xmlresponse