用C#編寫SOAP消息(轉)


因為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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM