因为SOAP消息是基于XML文档的,因此在C#中可以使用XmlTextWriter编写SOAP消息
首先定义一个XmlTextWriter
st = new MemoryStream(1024);//分配空间 XmlTextWriter tr = new XmlTextWriter(st,Encoding.UTF8); //初始化一个XmlTextWriter,编码方式为Encoding.UTF8
然后就可以开始写入了
tr.WriteStartDocument(); tr.WriteStartElement("soap","Envelope","http://schemas.xmlsoap.org/soap/envelope/"); tr.WriteAttributeString("xmlns","xsi",null,"http://www.w3.org/2001/XMLSchema-instance"); tr.WriteAttributeString("xmlns","xsd",null,"http://www.w3.org/2001/XMLSchema"); tr.WriteAttributeString("xmlns","soap",null,"http://schemas.xmlsoap.org/soap/envelope/"); tr.WriteStartElement("Header", "http://schemas.xmlsoap.org/soap/envelope/"); tr.WriteStartElement(null, "AuthInfo", "http://tempuri.org/"); tr.WriteElementString("UserName", "admin"); tr.WriteElementString("PassWord", "123"); tr.WriteEndElement(); tr.WriteEndElement(); tr.WriteStartElement("Body","http://schemas.xmlsoap.org/soap/envelope/"); tr.WriteStartElement(null,"GetAccount","http://tempuri.org/"); tr.WriteElementString("acctID","1"); tr.WriteEndElement(); tr.WriteEndElement(); tr.WriteEndDocument(); //////////////////////////////////////////////////////////////////////////
最后得到的SOAP消息如下:
?<?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:Header> <AuthInfo xmlns="http://tempuri.org/"> <UserName>admin</UserName> <PassWord>123</PassWord> </AuthInfo> </soap:Header> <soap:Body> <GetAccount xmlns="http://tempuri.org/"> <acctID>1</acctID> </GetAccount> </soap:Body> </soap:Envelope>
出处:http://blog.csdn.net/joyforce/article/details/5364972