IronPython系列:利用.NET SoapFormatter学习SOAP序列化

    Soap如何对.Net平台的各种数据类型进行序列化一直是我比较好奇的。虽然这方面有很多说明资料,但我还是想亲手体验下。所需要的工具很简单:.Net平台提供的SoapFormatter和可爱的IronPython。第一个目标就是哈希表Hashtable。实验代码如下:
from System.IO import *
from System.Collections import Hashtable
import clr
clr.AddReference("System.Runtime.Serialization.Formatters.Soap")
from System.Runtime.Serialization.Formatters.Soap import SoapFormatter
address = Hashtable()
address.Add("Fred", "987 Pine Road")
address.Add("Jeff", "123 Main Street")
fileStream = FileStream("DataFile.SOAP", FileMode.Create)
soapFormatter = SoapFormatter()
soapFormatter.Serialize(fileStream, address)

输出的文件如下:
<SOAP-ENV:Envelope xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd=" http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC=" http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV=" http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr=" http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle=" http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Hashtable id="ref-1" xmlns:a1=" http://schemas.microsoft.com/clr/ns/System.Collections">
<LoadFactor>0.72</LoadFactor>
<Version>2</Version>
<Comparer xsi:null="1"/>
<HashCodeProvider xsi:null="1"/>
<HashSize>11</HashSize>
<Keys href="#ref-2"/>
<Values href="#ref-3"/>
</a1:Hashtable>
<SOAP-ENC:Array id="ref-2" SOAP-ENC:arrayType="xsd:anyType[2]">
<item id="ref-4" xsi:type="SOAP-ENC:string">Jeff</item>
<item id="ref-5" xsi:type="SOAP-ENC:string">Fred</item>
</SOAP-ENC:Array>
<SOAP-ENC:Array id="ref-3" SOAP-ENC:arrayType="xsd:anyType[2]">
<item id="ref-6" xsi:type="SOAP-ENC:string">123 Main Street</item>
<item id="ref-7" xsi:type="SOAP-ENC:string">987 Pine Road</item>
</SOAP-ENC:Array>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
    从结果上看,Hashtable引用了keys(ref-2)和values(ref-3)两个数组,之后两个数组分别定义。
通过类似的方法我们就可以探寻SOAP如何序列化枚举Enumeration、字节数组Byte Array、结构体struct等其他数据类型了。
 
    参考文献:
http://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.formatters.soap.soapformatter(VS.80).aspx

你可能感兴趣的:(python,IronPython,SOAP序列化)