gsoap Supports serializing of application's native C and C++ data structures, which allows you to save and load of XML serialized data structures to and from files.
例如,一个通信服务器程序,我们通常要配置它启动哪些服务。标准的 xml 格式是:
常用的 xml 绑定工具有: gSoap,CodeSynthesis XSD 等。gSoap 使用简单,用户群广泛。所以以 gosp 为例进行讲解。
支持 UTF-8 、 multibyte character等数据类型。
1、构造 xsd
可以使用记事本写一个文件。
2 <!--语法定义开始. xml 数据元素(schema element ) 和 数据类型( element type) 的定义使用的命名空间(namespace)是 "http://www.w3.org/2000/10/XMLSchema" -->
3 <schema id = "book" xmlns="http://www.w3.org/2000/10/XMLSchema">
4 <!--根元素为 book-->
5 <element name="book">
6 <!-- 次级元素为 复合类型 -->
7 <complexType>
8 <sequence>
9 <!-- book 的第一个子元素是 title, 其 数据类型为 string,必须出现至少一次,0 表示可以不出现此元素 -->
10 <element name="title" type="string" minOccurs="1"/>
11 <!-- book 的第二个子元素是 publisher, 其 数据类型为 string,必须出现至少一次 -->
12 <element name="publisher" type="string" minOccurs="1"/>
13 </sequence>
14 <!-- "book" 结点有一个属性,其名称为 isbn,数据类型为 string -->
15 <attribute name="isbn" type="unsignedLong" use="required"/>
16 </complexType>
17 </element>
18 </schema>
一个xml 文件中,我们关注的是 element 元素。
根据以上规则,wsdl2h 工具可生成 xml 文件和 对应于xml文件的c++ class
相关链接:
xml 绑定技术介绍:
An Introduction to XML Data Binding in C++
介绍了 xml 绑定 技术的实现原理,与传统的DOM、SAX 等传统 xml 解析 技术的优势,及 xml 绑定技术的局限性。
xml Schema 用于为一个xml 文件定义了结构、内容和语意。w3c 为xml schema 语法定义了一个规范。
gSOAP 2.7.11 User Guide
gSoap 用户手册。第 1.4节 XML C/C++ Data Bindings: Mapping WSDL and XSD to C/C++ 介绍了用 怎样根据 xsd 文件,用 gsoap 工具包解析和生成 xml文件。7.5 How to Use the SOAP Serializers and Deserializers to Save and Load Application Data using XML Data Bindings
此时生成了 book.h文件。其中有类的定义如下:
{ public:
/// Element title of type xs:string.
string* title 1; ///< Required element.
/// Element publisher of type xs:string.
string* publisher 1; ///< Required element.
/// Attribute isbn of type xs:int.
@ULONG isbn 1; ///< Required attribute.
/// A handle to the soap struct that manages this instance (automatically set)
struct soap *soap ;
};
ns1 是默认的命名空间名,如果 wsdl2h 一次翻译了多个 xsd文件,则会依次生成 ns2,ns3...
struct soap 是一个堆空间,用于存放类成员。
@ 表示此成员是一个属性值。
若一个元素是可选的,则表现为对象的指针;若此元素值是必选的,则表现为对象。
参数说明:
程序中需要的文件:
stdsoap2.cpp stdsoap2.h ns1.msmap soapH.h soapC.cpp soapStub.h
最后生成的类定义如下:
2 {
3 public:
4 char *title; /* required element of type xsd:string */
5 char *publisher; /* required element of type xsd:string */
6 int isbn; /* required attribute */
7 struct soap *soap; /* transient */
8 public:
9 virtual int soap_type() const { return 8; } /* = unique id SOAP_TYPE__ns1__book */
10 virtual void soap_default(struct soap*);
11 virtual void soap_serialize(struct soap*) const;
12 virtual int soap_put(struct soap*, const char*, const char*) const;
13 virtual int soap_out(struct soap*, const char*, int, const char*) const;
14 virtual void *soap_get(struct soap*, const char*, const char*);
15 virtual void *soap_in(struct soap*, const char*, const char*);
16 _ns1__book() : title(NULL), publisher(NULL), isbn(0), soap(NULL) { }
17 virtual ~_ns1__book() { }
18 };