From 3939c9a6ceebbb237d8bdc041fd11f90ffc3b7ea Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Tue, 25 Feb 2014 09:22:06 +0200 Subject: Rename documentation/ to doc/ --- doc/cxx/hybrid/guide/figure-1.png | Bin 0 -> 11933 bytes doc/cxx/hybrid/guide/figure-1.svg | 217 ++ doc/cxx/hybrid/guide/guide.html2ps | 65 + doc/cxx/hybrid/guide/index.xhtml | 6521 +++++++++++++++++++++++++++++++ doc/cxx/hybrid/guide/makefile | 48 + doc/cxx/makefile | 20 + doc/cxx/parser/guide/figure-1.png | Bin 0 -> 34195 bytes doc/cxx/parser/guide/figure-1.svg | 373 ++ doc/cxx/parser/guide/guide.html2ps | 65 + doc/cxx/parser/guide/index.xhtml | 5383 ++++++++++++++++++++++++++ doc/cxx/parser/guide/makefile | 48 + doc/cxx/serializer/guide/figure-1.png | Bin 0 -> 30198 bytes doc/cxx/serializer/guide/figure-1.svg | 372 ++ doc/cxx/serializer/guide/guide.html2ps | 65 + doc/cxx/serializer/guide/index.xhtml | 6542 ++++++++++++++++++++++++++++++++ doc/cxx/serializer/guide/makefile | 48 + 16 files changed, 19767 insertions(+) create mode 100644 doc/cxx/hybrid/guide/figure-1.png create mode 100644 doc/cxx/hybrid/guide/figure-1.svg create mode 100644 doc/cxx/hybrid/guide/guide.html2ps create mode 100644 doc/cxx/hybrid/guide/index.xhtml create mode 100644 doc/cxx/hybrid/guide/makefile create mode 100644 doc/cxx/makefile create mode 100644 doc/cxx/parser/guide/figure-1.png create mode 100644 doc/cxx/parser/guide/figure-1.svg create mode 100644 doc/cxx/parser/guide/guide.html2ps create mode 100644 doc/cxx/parser/guide/index.xhtml create mode 100644 doc/cxx/parser/guide/makefile create mode 100644 doc/cxx/serializer/guide/figure-1.png create mode 100644 doc/cxx/serializer/guide/figure-1.svg create mode 100644 doc/cxx/serializer/guide/guide.html2ps create mode 100644 doc/cxx/serializer/guide/index.xhtml create mode 100644 doc/cxx/serializer/guide/makefile (limited to 'doc/cxx') diff --git a/doc/cxx/hybrid/guide/figure-1.png b/doc/cxx/hybrid/guide/figure-1.png new file mode 100644 index 0000000..b89cec8 Binary files /dev/null and b/doc/cxx/hybrid/guide/figure-1.png differ diff --git a/doc/cxx/hybrid/guide/figure-1.svg b/doc/cxx/hybrid/guide/figure-1.svg new file mode 100644 index 0000000..ccc79cd --- /dev/null +++ b/doc/cxx/hybrid/guide/figure-1.svg @@ -0,0 +1,217 @@ + + + + + + + + + + + + + image/svg+xml + + + + + + + + Object Model + Parser + + + Parser + + + + Serializer + + C++/Hybrid + + Application + + + C++/Parser + C++/Serializer + + diff --git a/doc/cxx/hybrid/guide/guide.html2ps b/doc/cxx/hybrid/guide/guide.html2ps new file mode 100644 index 0000000..92ef95d --- /dev/null +++ b/doc/cxx/hybrid/guide/guide.html2ps @@ -0,0 +1,65 @@ +@html2ps { + option { + toc: hb; + colour: 1; + hyphenate: 1; + titlepage: 1; + } + + datefmt: "%B %Y"; + + titlepage { + content: " +
+

Embedded C++/Hybrid Mapping

+

Getting Started Guide

+

 

+

 

+

 

+

 

+

 

+

 

+
+

Copyright © 2005-2011 CODE SYNTHESIS TOOLS CC

+ +

Permission is granted to copy, distribute and/or modify this + document under the terms of the + GNU Free + Documentation License, version 1.2; with no Invariant Sections, + no Front-Cover Texts and no Back-Cover Texts. +

+ +

This document is available in the following formats: + XHTML, + PDF, and + PostScript.

"; + } + + toc { + indent: 2em; + } + + header { + odd-right: $H; + even-left: $H; + } + + footer { + odd-left: $D; + odd-center: $T; + odd-right: $N; + + even-left: $N; + even-center: $T; + even-right: $D; + } +} + +body { + font-size: 12pt; + text-align: justify; +} + +pre { + font-size: 10pt; +} diff --git a/doc/cxx/hybrid/guide/index.xhtml b/doc/cxx/hybrid/guide/index.xhtml new file mode 100644 index 0000000..9bf3df1 --- /dev/null +++ b/doc/cxx/hybrid/guide/index.xhtml @@ -0,0 +1,6521 @@ + + + + + + Embedded C++/Hybrid Mapping Getting Started Guide + + + + + + + + + + + + + +
+
+ +
+ +
+
Embedded C++/Hybrid Mapping
+
Getting Started Guide
+ +

Copyright © 2005-2011 CODE SYNTHESIS TOOLS CC

+ +

Permission is granted to copy, distribute and/or modify this + document under the terms of the + GNU Free + Documentation License, version 1.2; with no Invariant Sections, + no Front-Cover Texts and no Back-Cover Texts. +

+ +

This document is available in the following formats: + XHTML, + PDF, and + PostScript.

+ +
+ +

Table of Contents

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Preface + + + +
About This Document
More Information
+
1Introduction + + + +
1.1Mapping Overview
1.2Benefits
+
2Hello World Example + + + + + + + +
2.1Writing XML Document and Schema
2.2Translating Schema to C++
2.3Implementing Application Logic
2.4Compiling and Running
2.5Adding Serialization
2.6A Minimal Version
+
3Mapping Configuration + + + + + + + + + +
3.1Standard Template Library
3.2Input/Output Stream Library
3.3C++ Exceptions
3.4XML Schema Validation
3.564-bit Integer Type
3.6Parser and Serializer Reuse
3.7Support for Polymorphism
3.8Custom Allocators
+
4Working with Object Models + + + + + + + + + + + +
4.1Namespaces
4.2Memory Management
4.3Enumerations
4.4Attributes and Elements
4.5Compositors
4.6Accessing the Object Model
4.7Modifying the Object Model
4.8Creating the Object Model from Scratch
4.9Customizing the Object Model
4.10Polymorphic Object Models
+
5Mapping for Built-In XML Schema Types + + + + + + + + + + + + + + + +
5.1Mapping for QName
5.2Mapping for NMTOKENS and IDREFSs
5.3Mapping for base54Binary and hexBinarys
5.4Time Zone Representation
5.5Mapping for date
5.6Mapping for dateTime
5.7Mapping for duration
5.8Mapping for gDay
5.9Mapping for gMonth
5.10Mapping for gMonthDay
5.11Mapping for gYear
5.12Mapping for gYearMonth
5.13Mapping for time
5.14Mapping for anyType
+
6Parsing and Serialization + + +
6.1Customizing Parsers and Serializers
+
7Binary Representation + + + + +
7.1CDR (Common Data Representation)
7.2XDR (eXternal Data Representation)
7.3Custom Representations
+
+
+ +

Preface

+ +

About This Document

+ +

The goal of this document is to provide you with an + understanding of the C++/Hybrid programming model and allow you + to efficiently evaluate XSD/e against your project's technical + requirements. As such, this document is intended for embedded + C++ developers and software architects who are looking for an + embedded XML processing solution. Prior experience with XML + and C++ is required to understand this document. Basic + understanding of XML Schema is advantageous but not expected + or required. +

+ + +

More Information

+ +

Beyond this guide, you may also find the following sources of + information useful:

+ + + + + +

1 Introduction

+ +

Welcome to CodeSynthesis XSD/e and the Embedded C++/Hybrid mapping. + XSD/e is a dependency-free W3C XML Schema to C++ compiler for mobile, + embedded, and light-weight applications. Embedded C++/Hybrid is an XML + Schema to C++ mapping that represents the data stored in XML as a + light-weight, statically-typed, in-memory object model. +

+ +

1.1 Mapping Overview

+ +

Based on a formal description of an XML vocabulary (schema), the + C++/Hybrid mapping produces a tree-like data structure suitable + for in-memory processing. The core of the mapping consists of C++ + classes that constitute the object model and are derived from + types defined in XML Schema. The C++/Hybrid mapping uses the + APIs provided by the + Embedded + C++/Parser and + Embedded + C++/Serializer + mappings to perform validation and parsing of XML to the object + model and validation and serialization of the object model to + XML. The following diagram illustrates the high-level architecture + of the C++/Hybrid mapping:

+ + +
+ +

The use of well-defined APIs presented by the C++/Parser and + C++/Serializer mappings for XML parsing and serialization + allows a number of advanced techniques, for example, customization + of parsing and serialization code, filtering of XML during + parsing or object model during serialization, as well as the hybrid, + partially event-driven, partially in-memory processing + where the XML document is delivered to the application as + parts of the object model. The last feature combines the + ease and convenience of the in-memory processing model + with the ability to minimize the use of RAM and process documents + that would otherwise not fit into memory. +

+ +

Besides reading from and writing to XML, the C++/Hybrid mapping + also supports saving the object model to and loading it from a + number of predefined as well as custom binary formats. Binary + representations contain only the data without any meta information + or markup. Consequently, saving to and loading from a binary + format can be an order of magnitude faster as well as result + in a much smaller application footprint compared to parsing and + serializing the same data in XML. Furthermore, the resulting + representation is normally several times smaller than the equivalent + XML.

+ +

The Embedded C++/Hybrid mapping was specifically designed and + optimized for mobile and embedded systems where hardware + constraints require high efficiency and economical use of + resources. As a result, the generated parsing and serialization + code is 2-10 times faster than general-purpose XML processors + while at the same time maintaining extremely low static and + dynamic memory footprints. For example, an executable that + performs validating XML parsing and serialization can be as small + as 150KB in size. The size can be further reduced by disabling + support for parsing or serialization as well as XML Schema + validation. +

+ +

The generated code and the runtime library are also highly-portable + and, in their minimal configuration, can be used without STL, RTTI, + iostream, C++ exceptions, and with the minimal use of C++ templates.

+ +

A typical application that uses the C++/Hybrid mapping for XML + processing performs the following three steps: it first + reads (parses) an XML document to an in-memory object model, it + then performs some useful computations on that object model which + may involve modification of the model, and finally it may write + (serialize) the modified object model back to XML. The next chapter + presents a simple application that performs these three steps. The + following chapters describe the Embedded C++/Hybrid mapping in more + detail.

+ +

1.2 Benefits

+ +

Traditional XML access APIs such as Document Object Model (DOM) + or Simple API for XML (SAX) as well as general-purpose XML Schema + validators have a number of drawbacks that make them less suitable + for creating mobile and embedded XML processing applications. These + drawbacks include: +

+ +
    +
  • Generic representation of XML in terms of elements, attributes, + and text forces an application developer to write a substantial + amount of bridging code that identifies and transforms pieces + of information encoded in XML to a representation more suitable + for consumption by the application logic.
  • + +
  • String-based flow control defers error detection to runtime. + It also reduces code readability and maintainability.
  • + +
  • Lack of type safety and inefficient use of resources due to + the data being represented as text.
  • + +
  • Extra validation code that is not used by the application.
  • + +
  • Resulting applications are hard to debug, change, and + maintain.
  • +
+ +

In contrast, a light-weight, statically-typed, vocabulary-specific + object model produced by the Embedded C++/Hybrid mapping allows + you to operate in your domain terms instead of the generic elements, + attributes, and text. Native data types are used to store the XML + data (for example, integers are stored as integers, not as text). + Validation code is included only for XML Schema constructs that + are used in the application. This results in efficient use of + resources and compact object code.

+ +

Furthermore, static typing helps catch errors at + compile-time rather than at run-time. Automatic code generation + frees you for more interesting tasks (such as doing something + useful with the information stored in the XML documents) and + minimizes the effort needed to adapt your applications to changes + in the document structure. To summarize, the C++/Hybrid object + model has the following key advantages over generic XML access + APIs:

+ +
    +
  • Ease of use. The generated code hides all the complexity + associated with parsing and serializing XML. This includes navigating + the structure and converting between the text representation and + data types suitable for manipulation by the application logic.
  • + +
  • Natural representation. The object representation allows + you to access the XML data using your domain vocabulary instead + of generic elements, attributes, and text.
  • + +
  • Concise code. With the object representation the + application implementation is simpler and thus easier + to read and understand.
  • + +
  • Safety. The generated object model is statically + typed and uses functions instead of strings to access the + information. This helps catch programming errors at compile-time + rather than at runtime.
  • + +
  • Maintainability. Automatic code generation minimizes the + effort needed to adapt the application to changes in the + document structure. With static typing, the C++ compiler + can pin-point the places in the client code that need to be + changed.
  • + +
  • Efficiency. If the application makes repetitive use + of the data extracted from XML, then the C++/Hybrid object model + is more efficient because the navigation is performed using + function calls rather than string comparisons and the XML + data is extracted only once. The runtime memory + usage is also reduced due to more efficient data storage + (for instance, storing numeric data as integers instead of + strings) as well as the static knowledge of cardinality + constraints. + +

    Furthermore, the generated XML parsing and serialization code + combines validation and data-to-text conversion in a single step. + This makes the generated code much more efficient than traditional + architectures with separate stages for validation and data + conversion.

    +
  • +
+ + + + +

2 Hello World Example

+ +

In this chapter we will examine how to parse, access, modify, and + serialize a very simple XML document using the generated + C++/Hybrid object model as well as the XML parser and serializer. The + code presented in this chapter is based on the hello + example which can be found in the examples/cxx/hybrid/ + directory of the XSD/e distribution.

+ +

2.1 Writing XML Document and Schema

+ +

First, we need to get an idea about the structure + of the XML documents we are going to process. Our + hello.xml, for example, could look like this:

+ +
+<?xml version="1.0"?>
+<hello>
+
+  <greeting>Hello</greeting>
+
+  <name>sun</name>
+  <name>moon</name>
+  <name>world</name>
+
+</hello>
+  
+ +

Then we can write a description of the above XML in the + XML Schema language and save it into hello.xsd:

+ +
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="hello">
+    <xs:sequence>
+      <xs:element name="greeting" type="xs:string"/>
+      <xs:element name="name" type="xs:string" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="hello" type="hello"/>
+
+</xs:schema>
+  
+ +

Even if you are not familiar with XML Schema, it + should be easy to connect declarations in hello.xsd + to elements in hello.xml. The hello type + is defined as a sequence of the nested greeting and + name elements. Note that the term sequence in XML + Schema means that elements should appear in a particular order + as opposed to appearing multiple times. The name + element has its maxOccurs property set to + unbounded which means it can appear multiple times + in an XML document. Finally, the globally-defined hello + element prescribes the root element for our vocabulary. For an + easily-approachable introduction to XML Schema refer to + XML Schema Part 0: + Primer.

+ +

The above schema is a specification of our XML vocabulary; it tells + everybody what valid documents of our XML-based language should look + like. The next step is to compile the schema to generate the object + model and the parser.

+ + +

2.2 Translating Schema to C++

+ +

Now we are ready to translate our hello.xsd to C++. + To do this we invoke the XSD/e compiler from a terminal (UNIX) or + a command prompt (Windows): +

+ +
+$ xsde cxx-hybrid --generate-parser --generate-aggregate hello.xsd
+  
+ +

This invocation of the XSD/e compiler produces three pairs of C++ files: + hello.hxx and hello.cxx, + hello-pskel.hxx and hello-pskel.cxx, as well as + hello-pimpl.hxx and hello-pimpl.cxx. The + first pair contains the object model classes. The second pair contains + parser skeletons. Parser skeletons are generated by the C++/Parser + mapping which is automatically invoked by C++/Hybrid. + For now we can ignore parser skeletons except that we need to compile + them and link the result to our application. The last pair of files + contains parser implementations. They implement the parser skeletons + to create and populate the object model types from XML data. The generation + of parser skeletons and parser implementations is requested with the + --generate-parser XSD/e compiler option.

+ +

You may be wondering what is the --generate-aggregate + option for. This option instructs the XSD/e compiler to generate + parser and, as we will see later, serializer aggregates. The + generated parser implementation files mentioned above contain + a separate parser implementation class for each type defined + in XML Schema. These parser implementations need to be + instantiated and connected before we can use them to parse an XML document. + When you specify the --generate-aggregate option, + the XSD/e compiler generates a class (in the parser implementation + files), called parser aggregate, for each global element defined + in the schema (you can also generate a parser aggregate for a type + as well as control for which global elements parser aggregates + are generated, see the + XSD/e + Compiler Command Line Manual for more information). A parser + aggregate instantiates and connects all the necessary parser + implementations needed to parse an XML document with a given root + element. We will see how to use the parser aggregate for the + hello root element in the next section.

+ +

The following code fragment is taken from hello.hxx; it + shows what the C++ object model for our "Hello World" XML vocabulary + looks like: +

+ +
+class hello
+{
+public:
+  hello ();
+
+  // greeting
+  //
+  const std::string&
+  greeting () const;
+
+  std::string&
+  greeting ();
+
+  void
+  greeting (const std::string&);
+
+  // name
+  //
+  typedef xml_schema::string_sequence name_sequence;
+  typedef name_sequence::iterator name_iterator;
+  typedef name_sequence::const_iterator name_const_iterator;
+
+  const name_sequence&
+  name () const;
+
+  name_sequence&
+  name ();
+
+private:
+  ...
+};
+  
+ +

The hello C++ class corresponds to the + hello XML Schema type. For each element + in this type a set of accessor and modifier functions + are generated inside the hello class. Note + that the member functions for the greeting and + name elements are different because of the + different cardinalities these two elements have + (greeting is a required single element and + name is a sequence of elements).

+ +

It is also evident that the built-in XML Schema type + string is mapped to std::string. + The string_sequence class that is used in + the name_sequence type definition + has an interface similar to std::vector. The + mapping between the built-in XML Schema types and C++ types + is described in more detail in Chapter 5, + "Mapping for Built-in XML Schema Types".

+ + +

2.3 Implementing Application Logic

+ +

At this point we have all the parts we need to do something useful + with the information stored in our XML document: +

+ +
+#include <iostream>
+
+#include "hello.hxx"
+#include "hello-pimpl.hxx"
+
+using namespace std;
+
+int
+main (int argc, char* argv[])
+{
+  try
+  {
+    // Parse.
+    //
+    hello_paggr hello_p;
+    xml_schema::document_pimpl doc_p (hello_p.root_parser (),
+                                      hello_p.root_name ());
+    hello_p.pre ();
+    doc_p.parse (argv[1]);
+    hello* h = hello_p.post ();
+
+    // Print what we've got.
+    //
+    for (hello::name_const_iterator i = h->name ().begin ();
+         i != h->name ().end ();
+         ++i)
+    {
+      cout << h->greeting () << ", " << *i << "!" << endl;
+    }
+
+    delete h;
+  }
+  catch (const xml_schema::parser_exception& e)
+  {
+    cerr << argv[1] << ":" << e.line () << ":" << e.column ()
+         << ": " << e.text () << endl;
+    return 1;
+  }
+}
+  
+ +

The first part of our application creates a document parser + and parses the XML file specified in the command line to the + object model. The hello_paggr class is the parser + aggregate class we discussed earlier. Parsing is covered in more + detail in Chapter 6, "Parsing and Serialization". + The second part uses the returned object model to iterate over + names and print a greeting line for each of them. We also catch + and print the xml_schema::parser_exception exception + in case something goes wrong. +

+ +

2.4 Compiling and Running

+ +

After saving our application from the previous section in + driver.cxx, we are ready to compile our first + program and run it on the test XML document. On UNIX + this can be done with the following commands: +

+ +
+$ c++ -I.../libxsde -c driver.cxx hello.cxx hello-pskel.cxx \
+  hello-pimpl.cxx
+
+$ c++ -o driver driver.o hello.o hello-pskel.o hello-pimpl.o \
+  .../libxsde/xsde/libxsde.a
+
+$ ./driver hello.xml
+Hello, sun!
+Hello, moon!
+Hello, world!
+  
+ +

Here .../libxsde represents the path to the + libxsde directory in the XSD/e distribution.

+ +

We can also test the error handling. To test XML well-formedness + checking, we can try to parse hello.hxx:

+ +
+$ ./driver hello.hxx
+hello.hxx:1:0: not well-formed (invalid token)
+  
+ +

We can also try to parse a valid XML but not from our + vocabulary, for example hello.xsd:

+ +
+$ ./driver hello.xsd
+hello.xsd:2:57: unexpected element encountered
+  
+ +

2.5 Adding Serialization

+ +

While parsing and accessing the XML data may be everything + you need, there are applications that require creating new + or modifying existing XML documents. To request the generation + of serialization support we will need to add the + --generate-serializer option to our XSD/e + compiler invocation:

+ +
+$ xsde cxx-hybrid --generate-parser --generate-serializer \
+  --generate-aggregate hello.xsd
+  
+ +

This will result in two additional pairs of C++ files: + hello-sskel.hxx and hello-sskel.cxx, as well as + hello-simpl.hxx and hello-simpl.cxx. + Similar to the parser files, the first pair contains serializer + skeletons (generated by the C++/Serializer mapping) and the second + pair contains serializer implementations as well as the serializer + aggregate for the hello root element.

+ +

Let us first examine an application that modifies an existing + object model and serializes it back to XML:

+ +
+#include <iostream>
+
+#include "hello.hxx"
+#include "hello-pimpl.hxx"
+#include "hello-simpl.hxx"
+
+using namespace std;
+
+int
+main (int argc, char* argv[])
+{
+  try
+  {
+    // Parse.
+    //
+    hello_paggr hello_p;
+    xml_schema::document_pimpl doc_p (hello_p.root_parser (),
+                                      hello_p.root_name ());
+    hello_p.pre ();
+    doc_p.parse (argv[1]);
+    hello* h = hello_p.post ();
+
+    // Change the greeting phrase.
+    //
+    h->greeting ("Hi");
+
+    // Add another entry to the name sequence.
+    //
+    h->name ().push_back ("mars");
+
+    // Serialize the modified object model to XML.
+    //
+    hello_saggr hello_s;
+    xml_schema::document_simpl doc_s (hello_s.root_serializer (),
+                                      hello_s.root_name ());
+    hello_s.pre (*h);
+    doc_s.serialize (cout, xml_schema::document_simpl::pretty_print);
+    hello_s.post ();
+
+    delete h;
+  }
+  catch (const xml_schema::parser_exception& e)
+  {
+    cerr << argv[1] << ":" << e.line () << ":" << e.column ()
+         << ": " << e.text () << endl;
+    return 1;
+  }
+  catch (const xml_schema::serializer_exception& e)
+  {
+    cerr << "error: " << e.text () << endl;
+    return 1;
+  }
+}
+  
+ +

First, our application parses an XML document and obtains its + object model as in the previous example. Then it changes the + greeting string and adds another entry to the list of names. + Finally, it creates a document serializer and serializes the + object model back to XML. The hello_saggr class + is the serializer aggregate class we discussed earlier.

+ +

The resulting XML is written to the standard output (cout) + for us to inspect. We could have also written the result to a + file or memory buffer by creating an instance of std::ofstream + or std::ostringstream and passing it to + serialize() instead of cout. + The second argument in the call to + serialize() is a flag that requests pretty-printing + of the resulting XML document. You would normally specify this flag + during testing to obtain easily-readable XML and remove it + in production to get faster serialization and smaller documents. + Serialization is covered in more detail in Chapter 6, + "Parsing and Serialization".

+ +

If we now compile and run this application (don't forget to + compile and link hello-sskel.cxx and + hello-simpl.cxx), we will see the + output as shown in the following listing:

+ +
+<hello>
+  <greeting>Hi</greeting>
+  <name>sun</name>
+  <name>moon</name>
+  <name>world</name>
+  <name>mars</name>
+</hello>
+  
+ +

+ We can also test XML Schema validation. We can "accidently" + remove all the names from the object model by adding the following + after: push_back ("mars"):

+ +
+h->name ().clear ();
+  
+ +

This will violate our vocabulary specification which requires + at least one name element to be present. If we + make the above change and recompile our application, we will + get the following output:

+ +
+$ ./driver hello.xml
+error: expected element not encountered
+  
+ +

It is also possible to create and serialize an object model from + scratch as shown in the following example. For this case we + can remove the --generate-parser option since + we don't need support for XML parsing.

+ +
+#include <sstream>
+#include <iostream>
+
+#include "hello.hxx"
+#include "hello-simpl.hxx"
+
+using namespace std;
+
+int
+main (int argc, char* argv[])
+{
+  try
+  {
+    hello h;
+    h.greeting ("Hi");
+
+    hello::name_sequence& ns = h.name ();
+    ns.push_back ("Jane");
+    ns.push_back ("John");
+
+    // Serialize the object model to XML.
+    //
+    hello_saggr hello_s;
+    xml_schema::document_simpl doc_s (hello_s.root_serializer (),
+                                      hello_s.root_name ());
+    ostringstream ostr;
+
+    hello_s.pre (h);
+    doc_s.serialize (ostr, xml_schema::document_simpl::pretty_print);
+    hello_s.post ();
+
+    cout << ostr.str () << endl;
+  }
+  catch (const xml_schema::serializer_exception& e)
+  {
+    cerr << "error: " << e.text () << endl;
+    return 1;
+  }
+}
+  
+ +

In this example we used the generated default constructor to + create an empty instance of type hello. We then + set greeting and, to reduce typing, we obtained a reference to + the name sequence which we used to add a few names. The + serialization part is identical to the previous example except + this time we first save the XML representation into a string. + If we compile and run this program, it produces the following + output:

+ +
+<hello>
+  <greeting>Hi</greeting>
+  <name>Jane</name>
+  <name>John</name>
+</hello>
+  
+ +

2.6 A Minimal Version

+ +

The previous sections showed a number of examples that relied + on STL for strings, iostream of input/output and C++ exceptions + for error handling. + As was mentioned in the introduction and will be discussed + in further detail in the next chapter, the C++/Hybrid mapping + can be configured only to rely on the minimal subset of C++. + In this section we will implement an example that parses, + prints, modifies and serializes the object model without + relying on STL, iostream, or C++ exceptions.

+ +

The first step is to instruct the XSD/e compiler not to use + any of the above features in the generated code. You may also + need to re-configure and rebuild the XSD/e runtime library + (libxsde.a) to disable STL, iostream, and + exceptions.

+ +
+$ xsde cxx-hybrid --no-stl --no-iostream --no-exceptions \
+  --generate-parser --generate-serializer --generate-aggregate \
+  hello.xsd
+  
+ +

If you now study the generated hello.hxx file, + you will notice that the use of std::string type + is replaced with char*. When STL is disabled, + built-in XML Schema type string is mapped to a + C string. The following listing presents the content of + driver.cxx in full:

+ +
+#include <stdio.h>
+
+#include "people.hxx"
+
+#include "people-pimpl.hxx"
+#include "people-simpl.hxx"
+
+using namespace std;
+
+struct writer: xml_schema::writer
+{
+  virtual bool
+  write (const char* s, size_t n)
+  {
+    return fwrite (s, n, 1, stdout) == 1;
+  }
+
+  virtual bool
+  flush ()
+  {
+    return fflush (stdout) == 0;
+  }
+};
+
+int
+main (int argc, char* argv[])
+{
+  // Open the file or use STDIN.
+  //
+  FILE* f = fopen (argv[1], "rb");
+
+  if (f == 0)
+  {
+    fprintf (stderr, "%s: unable to open\n", argc);
+    return 1;
+  }
+
+  // Parse.
+  //
+  using xml_schema::parser_error;
+
+  parser_error pe;
+  bool io_error = false;
+  hello* h = 0;
+
+  do
+  {
+    hello_paggr hello_p;
+    xml_schema::document_pimpl doc_p (hello_p.root_parser (),
+                                      hello_p.root_name ());
+    if (pe = doc_p._error ())
+      break;
+
+    hello_p.pre ();
+
+    if (pe = hello_p._error ())
+      break;
+
+    char buf[4096];
+
+    do
+    {
+      size_t s = fread (buf, 1, sizeof (buf), f);
+
+      if (s != sizeof (buf) && ferror (f))
+      {
+        io_error = true;
+        break;
+      }
+
+      doc_p.parse (buf, s, feof (f) != 0);
+      pe = doc_p._error ();
+
+    } while (!pe && !feof (f));
+
+    if (io_error || pe)
+      break;
+
+    h = hello_p.post ();
+    pe = hello_p._error ();
+
+  } while (false);
+
+  fclose (f);
+
+  // Handle parsing errors.
+  //
+  if (io_error)
+  {
+    fprintf (stderr, "%s: read failure\n", argc);
+    return 1;
+  }
+
+  if (pe)
+  {
+    switch (pe.type ())
+    {
+    case parser_error::sys:
+      {
+        fprintf (stderr, "%s: %s\n", argc, pe.sys_text ());
+        break;
+      }
+    case parser_error::xml:
+      {
+        fprintf (stderr, "%s:%lu:%lu: %s\n",
+                 argc, pe.line (), pe.column (), pe.xml_text ());
+        break;
+      }
+    case parser_error::schema:
+      {
+        fprintf (stderr, "%s:%lu:%lu: %s\n",
+                 argc, pe.line (), pe.column (), pe.schema_text ());
+        break;
+      }
+    default:
+      break;
+    }
+
+    return 1;
+  }
+
+  // Print what we've got.
+  //
+  for (hello::name_const_iterator i = h->name ().begin ();
+       i != h->name ().end ();
+       ++i)
+  {
+    printf ("%s, %s!\n", h->greeting (), *i);
+  }
+
+  using xml_schema::strdupx;
+
+  // Change the greeting phrase.
+  //
+  char* str = strdupx ("Hi");
+
+  if (str == 0)
+  {
+    fprintf (stderr, "error: no memory\n");
+    delete h;
+    return 1;
+  }
+
+  h->greeting (str);
+
+  // Add another entry to the name sequence.
+  //
+  str = strdupx ("mars");
+
+  if (str == 0)
+  {
+    fprintf (stderr, "error: no memory\n");
+    delete h;
+    return 1;
+  }
+
+  if (h->name ().push_back (str) != 0)
+  {
+    // The sequence has already freed str.
+    //
+    fprintf (stderr, "error: no memory\n");
+    delete h;
+    return 1;
+  }
+
+  // Serialize.
+  //
+  using xml_schema::serializer_error;
+
+  serializer_error se;
+  writer w;
+
+  do
+  {
+    hello_saggr hello_s;
+    xml_schema::document_simpl doc_s (hello_s.root_serializer (),
+                                      hello_s.root_name ());
+    if (se = doc_s._error ())
+      break;
+
+    hello_s.pre (*h);
+
+    if (se = hello_s._error ())
+      break;
+
+    doc_s.serialize (w, xml_schema::document_simpl::pretty_print);
+
+    if (se = doc_s._error ())
+      break;
+
+    hello_s.post ();
+
+    se = hello_s._error ();
+
+  } while (false);
+
+  delete h;
+
+  // Handle serializer errors.
+  //
+  if (se)
+  {
+    switch (se.type ())
+    {
+    case serializer_error::sys:
+      {
+        fprintf (stderr, "error: %s\n", se.sys_text ());
+        break;
+      }
+    case serializer_error::xml:
+      {
+        fprintf (stderr, "error: %s\n", se.xml_text ());
+        break;
+      }
+    case serializer_error::schema:
+      {
+        fprintf (stderr, "error: %s\n", se.schema_text ());
+        break;
+      }
+    default:
+      break;
+    }
+
+    return 1;
+  }
+}
+  
+ +

The parsing and serialization parts of the above example got + quite a bit more complex due to the lack of exceptions and iostream + support. For more information on what's going on there, refer to + Chapter 6, "Parsing and Serialization". On the other + hand, the access and modification of the object model stayed + relatively unchanged. The only noticeable change is the use + of the xml_schema::strdupx function to create + C strings from string literals. We have to use this function + because the object model assumes ownership of the strings + passed. We also cannot use the standard C strdup + because the object model expects the strings to be allocated + with C++ operator new[] while C strdup + uses malloc (on most implementations operator + new is implemented in terms of malloc + so you can probably use strdup if you really + want to).

+ + + + + +

3 Mapping Configuration

+ +

The Embedded C++/Hybrid mapping has a number of configuration + parameters that determine the overall properties and behavior + of the generated code, such as the use of Standard Template + Library (STL), Input/Output Stream Library (iostream), C++ + exceptions, XML Schema validation, 64-bit integer types, as well as + parser and serializer implementation reuse styles. In the previous + chapter we have already got an overview of the changes to the + generated code that happen when we disable STL, iostream, and C++ + exceptions. In this chapter we will discuss these and other + configuration parameters in more detail.

+ +

In order to enable or disable a particular feature, the corresponding + configuration parameter should be set accordingly in the XSD/e runtime + library as well as specified during schema compilation with the XSD/e + command line options as described in the + XSD/e + Compiler Command Line Manual. +

+ +

While the XML documents can use various encodings, the C++/Hybrid + object model always stores character data in the same encoding, + called application encoding. The application encoding can either be + UTF-8 (default) or ISO-8859-1. To select a particular encoding, configure + the XSD/e runtime library accordingly and pass the --char-encoding + option to the XSD/e compiler when translating your schemas.

+ +

When using ISO-8859-1 as the application encoding, XML documents + being parsed may contain characters with Unicode values greater + than 0xFF which are unrepresentable in the ISO-8859-1 encoding. + By default, in such situations parsing will terminate with + an error. However, you can suppress the error by providing a + replacement character that should be used instead of + unrepresentable characters, for example:

+ +
+xml_schema::iso8859_1::unrep_char ('?');
+  
+ +

To revert to the default behavior, set the replacement character + to '\0'.

+ +

The underlying XML parser used by the mapping includes built-in + support for XML documents encoded in UTF-8, UTF-16, ISO-8859-1, + and US-ASCII. Other encodings can be supported by providing + application-specific decoder functions. The underlying XML + serializer used by C++/Hybrid produces the resulting + XML documents in the UTF-8 encoding.

+ +

3.1 Standard Template Library

+ +

To disable the use of STL you will need to configure the XSD/e + runtime without support for STL as well as pass the + --no-stl option to the XSD/e compiler when + translating your schemas.

+ +

When STL is disabled, all string-based XML Schema types + (see Chapter 5, "Mapping for Built-In XML Schema + Types") are mapped to C-style char* instead of + std::string. In this configuration when you set an + element or attribute value of a string-based type, the object + model assumes ownership of the string and expects that it was + allocated with operator new[]. To simplify + creation of such strings from string literals, the generated + code provides the strdupx and strndupx + functions in the xml_schema namespace. These functions + are similar to C strdup and strndup except + that they use operator new[] instead of malloc + to allocate the string:

+ +
+namespace xml_schema
+{
+  char*
+  strdupx (const char*);
+
+  char*
+  strndupx (const char*, size_t);
+}
+  
+ +

3.2 Input/Output Stream Library

+ +

To disable the use of iostream you will need to configure the + XSD/e runtime library without support for iostream as well as + pass the --no-iostream option to the XSD/e compiler + when translating your schemas. When iostream is disabled, a + number of overloaded parse() and serialize() + functions in the document parser (xml_schema::document_pimpl) + and document serializer (xml_schema::document_simpl) become + unavailable. See + Chapter 7, + "Document Parser and Error Handling" in the Embedded + C++/Parser Mapping Getting Started Guide and + Chapter 8, + "Document Serializer and Error Handling" in the Embedded + C++/Serializer Mapping Getting Started Guide for details. +

+ +

3.3 C++ Exceptions

+ +

To disable the use of C++ exceptions, you will need to configure + the XSD/e runtime without support for exceptions as well as pass + the --no-exceptions option to the XSD/e compiler + when translating your schemas. When C++ exceptions are disabled, + the error conditions that may arise while parsing, serializing, + and modifying the object model are indicated with error codes + instead of exceptions. For more information on error handling + during parsing, see + Chapter 7, + "Document Parser and Error Handling" in the Embedded C++/Parser + Mapping Getting Started Guide. For more information on error handling + during serialization, see + Chapter 8, + "Document Serializer and Error Handling" in the Embedded + C++/Serializer Mapping Getting Started Guide. For more information on + error handling in the object model, see Chapter 4, "Working + with Object Models" below. +

+ +

3.4 XML Schema Validation

+ +

By default, XML Schema validation is enabled during both parsing + and serialization. To disable validation during parsing, you will + need to configure the XSD/e runtime to disable support for validation + in the C++/Parser mapping as well as pass the --suppress-parser-val + option to the XSD/e compiler when translating your schemas. To disable + validation during serialization, you will need to configure the XSD/e + runtime to disable support for validation in the C++/Serializer mapping + as well as pass the --suppress-serializer-val + option to the XSD/e compiler when translating your schemas. If you + are disabling validation during both parsing and serialization, you + can use the --suppress-validation option instead of the + two options mentioned above.

+ +

Disabling XML Schema validation allows to further increase the + parsing and serialization performance as well as reduce footprint in + cases where the data being parsed and/or serialized is known + to be valid.

+ +

3.5 64-bit Integer Type

+ +

By default the 64-bit long and unsignedLong + built-in XML Schema types are mapped to the 64-bit long long + and unsigned long long fundamental C++ types. To + disable the use of these types in the mapping you will need to + configure the XSD/e runtime accordingly as well as pass + the --no-long-long option to the XSD/e compiler + when translating your schemas. When the use of 64-bit integral + C++ types is disabled the long and + unsignedLong XML Schema built-in types are mapped + to long and unsigned long fundamental + C++ types.

+ +

3.6 Parser and Serializer Reuse

+ +

When one type in XML Schema inherits from another, it is + often desirable to be able to reuse the parser and serializer + implementations corresponding to the base type in the parser + and serializer implementations corresponding to the derived type. + XSD/e provides support for two reuse styles: the so-called mixin + (generated when the --reuse-style-mixin option + is specified) and tiein (generated by default) styles. + The XSD/e runtime should be configured in accordance with the + reuse style used in the generated code. See Section 5.6, + "Parser Reuse" in the Embedded C++/Parser Mapping Getting Started + Guide and + Section 6.6, + "Serializer Reuse" in the Embedded C++/Serializer Mapping Getting + Started Guide for details.

+ +

3.7 Support for Polymorphism

+ +

By default the XSD/e compiler generates non-polymorphic code. If your + vocabulary uses XML Schema polymorphism in the form of xsi:type + and/or substitution groups, then you will need to configure the XSD/e + runtime with support for polymorphism, compile your schemas with the + --generate-polymorphic option to produce polymorphism-aware + code, as well as pass true as the last argument to the + xml_schema::document_pimpl and + xml_schema::document_simpl constructors (see + Chapter 6, "Parsing and Serialization" for details). + If some of your schemas do not require support for polymorphism then + you can compile them with the --runtime-polymorphic option + and still use the XSD/e runtime configured with polymorphism support. +

+ +

The XSD/e compiler can often automatically determine which types are + polymorphic based on the substitution group declarations. However, + if your XML vocabulary is not using substitution groups or if + substitution groups are defined in a separate schema, then you will + need to use the --polymorphic-type option to specify + which types are polymorphic. When using this option you only need + to specify the root of a polymorphic type hierarchy and the XSD/e + compiler will assume that all the derived types are also polymorphic. + Also note that you need to specify this option when compiling every + schema file that references the polymorphic type. Consider the following + two schemas as an example:

+ +
+<!-- base.xsd -->
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="base">
+    <xs:sequence>
+      <xs:element name="b" type="xs:int"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <!-- substitution group root -->
+  <xs:element name="base" type="base"/>
+
+</xs:schema>
+  
+ +
+<!-- derived.xsd -->
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <include schemaLocation="base.xsd"/>
+
+  <xs:complexType name="derived">
+    <xs:complexContent>
+      <xs:extension base="base">
+        <xs:sequence>
+          <xs:element name="d" type="xs:string"/>
+        </xs:sequence>
+      </xs:extension>
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:element name="derived" type="derived" substitutionGroup="base"/>
+
+</xs:schema>
+  
+ +

In this example we need to specify "--polymorphic-type base" + when compiling both schemas because the substitution group is declared + in a schema other than the one defining type base.

+ +

Another issue that may arise when compiling polymorphic schemas is + the situation where the XSD/e compiler is unaware of all the + derivations of a polymorphic type while generating parser and + serializer aggregates. As a result, the generated code may not + be able to parse and serialize these "invisible" to the compiler + types. The following example will help illustrate this case. + Consider a modified version of base.xsd from the + above example:

+ +
+<!-- base.xsd -->
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="base">
+    <xs:sequence>
+      <xs:element name="b" type="xs:int"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <!-- substitution group root -->
+  <xs:element name="base" type="base"/>
+
+  <xs:complexType name="root">
+    <xs:sequence>
+      <xs:element ref="base" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <!-- document root -->
+  <xs:element name="root" type="root"/>
+
+</xs:schema>
+  
+ +

Suppose we compile this schema as follows:

+ +
+$ xsde cxx-hybrid --generate-parser --generate-serializer \
+--generate-polymorphic --polymorphic-type base \
+--generate-aggregate --root-element root base.xsd
+  
+ +

The resulting parser and serializer aggregates for the root + element will not include the parser and serializer for the + derived type that can be used instead of the + base type. This is because the XSD/e compiler + has no knowledge of the derived's existence when + compiling base.xsd.

+ +

There are two ways to overcome this problem. The easier but + potentially slower approach is to compile all your schemas + at once, for example:

+ +
+$ xsde cxx-hybrid --generate-parser --generate-serializer \
+--generate-polymorphic --polymorphic-type base \
+--generate-aggregate --root-element root base.xsd derived.xsd
+  
+ +

This will make sure the XSD/e compiler "sees" all the derivations + of the polymorphic types. The other approach allows + you to explicitly specify, with the --polymorphic-schema + option, additional schemas that may contain derivations of the + polymorphic types. Using this approach we would compile + base.xsd and derived.xsd like this:

+ +
+$ xsde cxx-hybrid --generate-parser --generate-serializer \
+--generate-polymorphic --polymorphic-type base \
+--generate-aggregate --root-element root \
+--polymorphic-schema derived.xsd base.xsd
+
+$ xsde cxx-hybrid --generate-parser --generate-serializer \
+--generate-polymorphic --polymorphic-type base derived.xsd
+  
+ +

For information on how to use object models with polymorphic types, + refer to Section 4.10, "Polymorphic Object Models".

+ +

3.8 Custom Allocators

+ +

By default the XSD/e runtime and generated code use + the standard operators new and delete + to manage dynamic memory. However, it is possible to instead + use custom allocator functions provided by your application. + To achieve this, configure the XSD/e runtime library to use + custom allocator functions as well as pass the + --custom-allocator option to the XSD/e compiler + when translating your schemas. The signatures of the custom + allocator functions that should be provided by your application + are listed below. Their semantics should be equivalent to the + standard C malloc(), realloc(), and + free() functions.

+ +
+extern "C" void*
+xsde_alloc (size_t);
+
+extern "C" void*
+xsde_realloc (void*, size_t);
+
+extern "C" void
+xsde_free (void*);
+  
+ +

Note also that when custom allocators are enabled, any + dynamically-allocated object of which the XSD/e runtime + or generated code assume ownership should be allocated + using the custom allocation function. Similarly, if your + application assumes ownership of any dynamically-allocated + object returned by the XSD/e runtime or the generated code, + then such an object should be disposed of using the custom + deallocation function. To help with these tasks the generated + xml_schema namespace defines the following two + helper functions and, if C++ exceptions are enabled, automatic + pointer class:

+ +
+namespace xml_schema
+{
+  void*
+  alloc (size_t);
+
+  void
+  free (void*);
+
+  struct alloc_guard
+  {
+    alloc_guard (void*);
+    ~alloc_guard ();
+
+    void*
+    get () const;
+
+    void
+    release ();
+
+  private:
+    ...
+  };
+}
+  
+ +

If C++ exceptions are disabled, these functions are equivalent + to xsde_alloc() and xsde_free(). + If exceptions are enabled, xml_schema::alloc() + throws std::bad_alloc on memory allocation failure.

+ +

The following code fragment shows how to create and destroy a + dynamically-allocated object with custom allocators when C++ + exceptions are disabled:

+ +
+void* v = xml_schema::alloc (sizeof (type));
+
+if (v == 0)
+{
+  // Handle out of memory condition.
+}
+
+type* x = new (v) type (1, 2);
+
+...
+
+if (x)
+{
+  x->~type ();
+  xml_schema::free (x);
+}
+  
+ +

The equivalent code fragment for configurations with C++ exceptions + enabled is shown below:

+ +
+xml_schema::alloc_guard g (xml_schema::alloc (sizeof (type)));
+type* x = new (g.get ()) type (1, 2);
+g.release ();
+
+...
+
+if (x)
+{
+  x->~type ();
+  xml_schema::free (x);
+}
+  
+ +

For a complete example that shows how to use custom allocators, see + the allocator example which can be found in the + examples/cxx/hybrid/ directory of the XSD/e distribution.

+ + + + +

4 Working with Object Models

+ +

As we have seen in the previous chapters, the XSD/e compiler generates + a C++ class for each type defined in XML Schema. Together these classes + constitute an object model for an XML vocabulary. In this chapter we + will take a closer look at different parts that comprise an + object model class as well as how to create, access, and modify + object models.

+ +

In this chapter we will use the following schema that describes a + collection of person records. We save it in people.xsd:

+ +
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:simpleType name="gender">
+    <xs:restriction base="xs:string">
+      <xs:enumeration value="male"/>
+      <xs:enumeration value="female"/>
+    </xs:restriction>
+  </xs:simpleType>
+
+  <xs:complexType name="person">
+    <xs:sequence>
+      <xs:element name="first-name" type="xs:string"/>
+      <xs:element name="middle-name" type="xs:string" minOccurs="0"/>
+      <xs:element name="last-name" type="xs:string"/>
+      <xs:element name="gender" type="gender"/>
+      <xs:element name="age" type="xs:unsignedShort"/>
+    </xs:sequence>
+    <xs:attribute name="id" type="xs:unsignedInt" use="required"/>
+  </xs:complexType>
+
+  <xs:complexType name="people">
+    <xs:sequence>
+      <xs:element name="person" type="person" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="people" type="people"/>
+
+</xs:schema>
+  
+ +

A sample XML instance to go along with this schema is saved + in people.xml:

+ +
+<?xml version="1.0"?>
+<people>
+
+  <person id="1">
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+
+  <person id="2">
+    <first-name>Jane</first-name>
+    <middle-name>Mary</middle-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+
+</people>
+  
+ +

Compiling people.xsd with the XSD/e compiler results + in three generated object model classes: gender, + person and people. Here is how they + look with STL enabled:

+ +
+// gender (fixed-length)
+//
+class gender
+{
+public:
+  enum value_type
+  {
+    male,
+    female
+  };
+
+  gender ();
+  gender (value_type);
+  gender (const gender&);
+  gender& operator= (const gender&);
+
+  void
+  value (value_type);
+
+  operator value_type () const;
+
+  const char*
+  string () const;
+
+private:
+  ...
+};
+
+// person (fixed-length)
+//
+class person
+{
+public:
+  person ();
+  person (const person&);
+  person& operator= (const person&);
+
+  // id
+  //
+  unsigned int
+  id () const;
+
+  unsigned int&
+  id ();
+
+  void
+  id (unsigned int);
+
+  // first-name
+  //
+  const std::string&
+  first_name () const;
+
+  std::string&
+  first_name ();
+
+  void
+  first_name (const std::string&);
+
+  // middle-name
+  //
+  bool
+  middle_name_present () const;
+
+  void
+  middle_name_present (bool);
+
+  const std::string&
+  middle_name () const;
+
+  std::string&
+  middle_name ();
+
+  void
+  middle_name (const std::string&);
+
+  // last-name
+  //
+  const std::string&
+  last_name () const;
+
+  std::string&
+  last_name ();
+
+  void
+  last_name (const std::string&);
+
+  // gender
+  //
+  const ::gender&
+  gender () const;
+
+  ::gender&
+  gender ();
+
+  void
+  gender (const ::gender&);
+
+  // age
+  //
+  unsigned short
+  age () const;
+
+  unsigned short&
+  age ();
+
+  void
+  age (unsigned short);
+
+private:
+  ...
+};
+
+// people (variable-length)
+//
+class people
+{
+public:
+  people ();
+
+private:
+  people (const people&);
+  people& operator= (const people&);
+
+public:
+  // person
+  //
+  typedef xml_schema::fix_sequence<person> person_sequence;
+  typedef person_sequence::iterator person_iterator;
+  typedef person_sequence::const_iterator person_const_iterator;
+
+  const person_sequence&
+  person () const;
+
+  person_sequence&
+  person ();
+
+private:
+  ...
+};
+  
+ +

We will examine these classes in detail in the subsequent + sections.

+ +

4.1 Namespaces

+ +

XSD/e maps XML namespaces specified in the targetNamespace + attribute in XML Schema to one or more nested C++ namespaces. By + default, a namespace URI is mapped to a sequence of C++ namespace + names by removing the protocol and host parts and splitting the + rest into a sequence of names with '/' as the name + separator. For example, the http://www.codesynthesis.com/cs/my + XML namespace is mapped to the cs::my C++ namespace.

+ +

The default mapping of namespace URIs to C++ namespaces + can be altered using the --namespace-map and + --namespace-regex compiler options. For example, + to map the http://www.codesynthesis.com/my XML + namespace to the cs::my C++ namespace, we can use + the following option:

+ +
+--namespace-map http://www.codesynthesis.com/my=cs::my
+  
+ +

A vocabulary without a namespace is mapped to the global scope. This + also can be altered with the above options by using an empty name + for the XML namespace. For example, we could place the generated + object model classes for the people.xsd schema + into the records C++ namespace by adding the following + option:

+ +
+--namespace-map =records
+  
+ + +

4.2 Memory Management

+ +

To ensure that objects are allocated and passed efficiently, + the C++/Hybrid mapping divides all object model types into + fixed-length and variable-length. A type is variable-length + if any of the following is true:

+ +
    +
  1. it is an XML Schema list type
  2. + +
  3. it is an XML Schema union type and STL is disabled
  4. + +
  5. it derives from a variable-length type
  6. + +
  7. it contains an element or attribute of a variable-length type
  8. + +
  9. it contains an element or compositor (sequence + or choice) with maxOccurs + greater than one
  10. + +
  11. it is recursive (that is, one of its elements contains + a reference, directly or indirectly, to the type itself)
  12. + +
  13. it is polymorphic (see Section 4.10, "Polymorphic + Object Models" for details)
  14. +
+ +

The following build-in XML Schema types are variable-length: + base64Binary, hexBinary, NMTOKENS, + and IDREFS. Furthermore, if STL is disabled, all + string-based build-in XML Schema types are variable-length, + namely: string, normalizedString, + token, Name, NMTOKEN, + NCName, language, QName, + ID, IDFER, and anyURI.

+ +

Otherwise, a type is fixed-length. As you might have noticed from + the previous code listings, the XSD/e compiler adds a comment before + each generated object model class that states whether it is fixed or + variable-length. For example, the people type is + variable-length because it contains a sequence of person + elements (maxOccurs="unbounded"). If we recompile + the people.xsd schema with the --no-stl + option, the person type will also become variable-length + since it contains elements of the string built-in type. + And when STL is disabled, string is variable-length.

+ +

The object model uses different methods for storing and passing + around fixed-length and variable-length types. Instances of + fixed-length types are stored and passed by value since it is + cheaper to copy than to allocate them dynamically (in the + STL case, the std::string is expected to support the + referenced-counted copy-on-write optimization, which makes + copying cheap).

+ +

Variable-length types are always allocated dynamically and + are stored and passed as pointers. Because copying an instance + of a variable-length type can be expensive, such types make + their copy constructor and copy assignment operators unavailable.

+ +

When you set a value of an element or attribute of a + variable-length type, the object model assumes ownership of + the pointed to object. Unless you are using custom allocators + (see Section 3.8, "Custom Allocators"), + the object model expects you to allocate such an object with + operator new and will eventually delete it + with operator delete.

+ +

If you wish to make copies of variable-length objects, then + you can request the generation of the object cloning functions + with the --generate-clone compiler + option. When this option is specified, each variable-length + type implements the _clone() function which returns + a dynamically-allocated copy of the object or NULL + if the allocation failed and C++ exceptions are disabled (see + Section 3.3, "C++ Exceptions").

+ +

You can also request generation of detach functions with the + --generate-detach compiler option. These functions + allow you to detach a variable-length object from the object model. + As an example, let us extend + our people.xsd schema with the following type:

+ +
+<xs:complexType name="staff">
+  <xs:sequence>
+    <xs:element name="permanent" type="people"/>
+    <xs:element name="contract" type="people"/>
+  </xs:sequence>
+</xs:complexType>
+  
+ +

If we compile it with XSD/e and specify the + --generate-clone and --generate-detach + options, we will get the following C++ class:

+ +
+// staff (variable-length)
+//
+class staff
+{
+public:
+  staff ();
+
+  staff*
+  _clone () const;
+
+private:
+  staff (const staff&);
+  staff& operator= (const staff&);
+
+public:
+  // permanent
+  //
+  const people&
+  permanent () const;
+
+  people&
+  permanent ();
+
+  void
+  permanent (people*);
+
+  people*
+  permanent_detach ();
+
+  // contract
+  //
+  const people&
+  contract () const;
+
+  people&
+  contract ();
+
+  void
+  contract (people*);
+
+  people*
+  contract_detach ();
+
+private:
+  ...
+};
+  
+ +

Notice that unlike, say, the first_name() modifier + function in the person class, the permanent() + and contract() modifiers expect a pointer to the + people object. The following listing shows how + we can create and populate an instance of the staff + class. The use of smart pointers to hold the results of dynamic + allocations is omitted for brevity:

+ +
+people* per = new people;
+people* con = new people;
+
+// Populate per and con.
+
+staff s;
+s->permanent (per) // Assumes ownership of per.
+s->contract (con)  // Assumes ownership of con.
+  
+ +

4.3 Enumerations

+ +

By default, string-based types that use XML Schema restriction by + enumeration are mapped to C++ classes with semantics similar to + C++ enum (you can suppress this mapping and instead get the plain + inheritance by specifying the --suppress-enum compiler + option). The following code fragment again shows the C++ class that + was generated for the gender XML Schema type presented + at the beginning of this chapter:

+ +
+// gender (fixed-length)
+//
+class gender
+{
+public:
+  enum value_type
+  {
+    male,
+    female
+  };
+
+  gender ();
+  gender (value_type);
+  gender (const gender&);
+  gender& operator= (const gender&);
+
+  void
+  value (value_type);
+
+  operator value_type () const;
+
+  const char*
+  string () const;
+
+private:
+  value_type v_;
+};
+
+ +

The gender class defines the underlying C++ enum type + (value_type) with enumerators corresponding to the + enumeration elements in XML Schema. The class also + defines the default constructor, copy constructor, constructor + with the underlying enum type as its argument, and the assignment + operator. The gender class also supports the implicit + conversion to the underlying enum type and the explicit conversion + to string via the string() function. Finally, it + provides the value() modifier function which allows you + to set the underlying enum value explicitly. Note also that such an + enumeration class is always fixed-length since it only contains the + C++ enum value. The following example shows how we can use the + gender class:

+ +
+gender g = gender::male;
+g = gender::female;
+g.value (gender::female); // Same as above.
+
+cerr << g.string () << endl;
+
+if (g != gender::male)
+  ...
+
+switch (g)
+{
+case gender::male:
+  ...
+case gender::female:
+  ...
+}
+  
+ + +

4.4 Attributes and Elements

+ +

As we have seen before, XSD/e generates a different + set of member functions for elements with different cardinalities. + The C++/Hybrid mapping divides all the possible element and attribute + cardinalities into three cardinality classes: + one, optional, and sequence.

+ +

The one cardinality class covers all elements that should + occur exactly once as well as the required attributes. In our + example, the first-name, last-name, + gender, and age elements as well as + the id attribute belong to this cardinality class. + The following code fragment again shows the accessor and modifier + functions that are generated for the first-name element + in the person class:

+ +
+class person
+{
+  // first-name
+  //
+  const std::string&
+  first_name () const;
+
+  std::string&
+  first_name ();
+
+  void
+  first_name (const std::string&);
+};
+  
+ +

The first two accessor functions return read-only (constant) and + read-write references to the element's value, respectively. The + modifier function sets the new value for the element. Note that + the signature of the modifier function varies depending on + whether the element or attribute is of a fixed or variable-length + type, as was discussed in the previous section.

+ +

The optional cardinality class covers all elements that + can occur zero or one time as well as optional attributes. In our + example, the middle-name element belongs to this + cardinality class. The following code fragment again shows the + accessor and modifier functions that are generated for this element + in the person class:

+ +
+class person
+{
+  // middle-name
+  //
+  bool
+  middle_name_present () const;
+
+  void
+  middle_name_present (bool);
+
+  const std::string&
+  middle_name () const;
+
+  std::string&
+  middle_name ();
+
+  void
+  middle_name (const std::string&);
+};
+  
+ +

Compared to the one cardinality class, optional adds + functions for querying and modifying the member's presence status. + The following example shows how we can use these functions:

+ +
+person& p = ...
+
+if (p.middle_name_present ())
+{
+  cout << p.middle_name () << endl;
+  p.middle_name_present (false); // Reset to the "not present" state.
+}
+  
+ +

If an optional member is of a variable-length type, then the second + _present() function is omitted. This is done to help + detect programming errors that result from a type becoming + variable-length due to schema changes. In this situation, before + the type becomes variable-length, calling the presence function + with true as its argument and then accessing the + member is valid. Once the type becomes variable-length, the + same sequence of calls would lead to a runtime error. By + omitting the second _present() function for + variable-length types, this kind of errors can be detected + at compile time. To reset an optional member of a variable-length + type you can call the member modifier function with NULL + as its argument. For example, if the middle_name + member was of a variable-length type, then the above code fragment + would look like this:

+ +
+person& p = ...
+
+if (p.middle_name_present ())
+{
+  cout << *p.middle_name () << endl;
+  p.middle_name (0); // Reset to the "not present" state.
+}
+  
+ + +

There are two cases in the optional cardinality class that + are handled differently. These are optional attributes with default + and fixed values. When an optional attribute declaration in XML Schema + specifies a default or fixed value and such an attribute is not present + in the XML document, the attribute is assumed to have the default or + fixed value, respectively. Furthermore, if an attribute with the + fixed value is set in the XML document, then the attribute value + should be the same as its fixed value.

+ +

For an optional attribute with a default value, the functions for + querying and modifying the attribute's presence status are replaced + with functions that allow you to determine whether the attribute has + the default value. The accessor functions can be called at any time + since an optional attribute with a default value always has some + value. Also an extra static function is provided to allow you to + obtain the default value. Consider the following modification to + the person type which adds the verified + attribute with the default value:

+ +
+<xs:complexType name="person">
+  <xs:sequence>
+    <xs:element name="first-name" type="xs:string"/>
+    ...
+  </xs:sequence>
+  <xs:attribute name="id" type="xs:unsignedInt" use="required"/>
+  <xs:attribute name="verified" type="xs:boolean" default="false"/>
+</xs:complexType>
+  
+ +

The code fragment below shows the accessor and modifier functions + that are generated for this new attribute in the person + class:

+ +
+class person
+{
+  // verified
+  //
+  bool
+  verified_default () const;
+
+  void
+  verified_default (bool);
+
+  bool
+  verified () const;
+
+  bool&
+  verified ();
+
+  void
+  verified (bool);
+
+  static bool
+  verified_default_value ();
+};
+  
+ +

When we create an object of the person class, the + verified member is automatically initialized to the + default value. The following example shows how we can manipulate + the verified attribute value:

+ +
+person p; // verified is set to the default value (false).
+
+if (p.verified_default ())
+  p.verified (true);
+else
+  p.verified_default (true); // Revert to the default value.
+
+bool v = p.verified (); // Ok, can always be called.
+bool vd = person::verified_default_value ();
+  
+ +

Note that modifying an attribute of a variable-length type via + the reference when the attribute is set to the default value is + illegal since this will modify the default value shared by all + instances. For example:

+ +
+type& x = ...
+
+if (x.foo_default ())
+{
+  foo& f = x.foo (); // foo is variable-length, for example NMTOKENS
+  f.push_back ("aaa"); // Illegal.
+}
+
+if (x.foo_default ())
+{
+  foo* f = new foo;
+  f->push_back ("aaa");
+  x.foo (f); // Ok.
+}
+  
+ +

Because an attribute with a fixed value can only be set to that + value, only the read-only (constant) accessor and the static + function for obtaining the fixed value are provided for such + attributes. Similar to the default values, members with fixed + values of a newly created object are automatically initialized + to their respective fixed values. Consider the following + modification to the verified attribute from the + schema above:

+ +
+<xs:complexType name="person">
+  ...
+  <xs:attribute name="verified" type="xs:boolean" fixed="true"/>
+</xs:complexType>
+  
+ +

The code fragment below shows the accessor functions that are + generated for this attribute in the person + class:

+ +
+class person
+{
+  // verified
+  //
+  bool
+  verified () const;
+
+  static bool
+  verified_fixed_value ();
+};
+  
+ +

During serialization, attributes that are set to default and fixed + values are explicitly specified in the resulting XML document. + You can use the --omit-default-attributes XSD/e + compiler option to omit such attributes from the serialized XML.

+ +

The sequence cardinality class covers all elements + that can occur more than once. In our example, the + person element in the people type + belongs to this cardinality class. The following code fragment shows + again the type definitions as well as the accessor and modifier + functions that are generated for this element in the people + class:

+ +
+class people
+{
+  // person
+  //
+  typedef xml_schema::fix_sequence<person> person_sequence;
+  typedef person_sequence::iterator person_iterator;
+  typedef person_sequence::const_iterator person_const_iterator;
+
+  const person_sequence&
+  person () const;
+
+  person_sequence&
+  person ();
+};
+  
+ +

The person_sequence type is a sequence container for the + element's values. It has an interface similar to std::vector + and we will discuss it in more detail shortly. The person_iterator + and person_const_iterator types are read-write and read-only + (constant) iterators for the person_sequence + container.

+ +

Unlike other two cardinality classes, the sequence class + only provides accessor functions that return read-only (constant) + and read-write references to the sequence container. The + modification of the element values is performed my manipulating + the returned sequence container and elements that it contains.

+ +

In the remainder of this section we will examine the interfaces + of the sequence containers which differ slightly depending on + whether the element type is fixed or variable-length and whether + C++ exceptions are enabled. Also, when STL is disabled, string + sequences have a special interface which is also discussed + below.

+ +

When exceptions are enabled, the fixed-length type sequences + are implemented in terms of the following class template:

+ +
+namespace xml_schema
+{
+  template <typename T>
+  class fix_sequence
+  {
+  public:
+    typedef T         value_type;
+    typedef T*        pointer;
+    typedef const T*  const_pointer;
+    typedef T&        reference;
+    typedef const T&  const_reference;
+
+    typedef size_t    size_type;
+    typedef ptrdiff_t difference_type;
+
+    typedef T*        iterator;
+    typedef const T*  const_iterator;
+
+  public:
+    fix_sequence ();
+
+    void
+    swap (fix_sequence&);
+
+  private:
+    fix_sequence (const fix_sequence&);
+
+    fix_sequence&
+    operator= (fix_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    T&
+    front ();
+
+    const T&
+    front () const;
+
+    T&
+    back ();
+
+    const T&
+    back () const;
+
+    T&
+    operator[] (size_t);
+
+    const T&
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    push_back (const T&);
+
+    iterator
+    insert (iterator, const T&);
+
+    void
+    reserve (size_t);
+
+    void
+    assign (const T* src, size_t n);
+  };
+}
+  
+ +

When C++ exceptions are disabled, the signatures of the + push_back(), insert(), + reserve(), and assign() functions + change as follows:

+ +
+namespace xml_schema
+{
+  template <typename T>
+  class fix_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (const T&);
+
+    error
+    insert (iterator, const T&);
+
+    error
+    insert (iterator, const T&, iterator& result);
+
+    error
+    reserve (size_t);
+
+    error
+    assign (const T* src, size_t n);
+  };
+}
+  
+ +

That is, the functions that may require memory allocation + now return an error code that you will need to check in + order to detect the out of memory condition.

+ +

When exceptions are enabled, the variable-length type sequences + are implemented in terms of the following class template:

+ +
+namespace xml_schema
+{
+  template <typename T>
+  class var_sequence
+  {
+  public:
+    typedef T         value_type;
+    typedef T*        pointer;
+    typedef const T*  const_pointer;
+    typedef T&        reference;
+    typedef const T&  const_reference;
+
+    typedef size_t    size_type;
+    typedef ptrdiff_t difference_type;
+
+    typedef <implementation details> iterator;
+    typedef <implementation details> const_iterator;
+
+  public:
+    var_sequence ();
+
+    void
+    swap (var_sequence&);
+
+  private:
+    var_sequence (const var_sequence&);
+
+    var_sequence&
+    operator= (var_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    T&
+    front ();
+
+    const T&
+    front () const;
+
+    T&
+    back ();
+
+    const T&
+    back () const;
+
+    T&
+    operator[] (size_t);
+
+    const T&
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    push_back (T*);
+
+    iterator
+    insert (iterator, T*);
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    reserve (size_t);
+
+    T*
+    detach (iterator);
+
+    void
+    attach (iterator, T*);
+  };
+}
+  
+ +

Most of this interface is identical to the fixed-length type + version except for the push_back(), and + insert() functions. Similar to the modifier + functions for elements and attributes of variable-length + types, these two functions expect a pointer to the + dynamically-allocated instance of the type and assume + ownership of the passed object. To simplify error handling, + these two functions delete the passed object if the reallocation + of the underlying sequence buffer fails. The var_sequence + class template also provides the detach() and attach() + functions. The detach() function allows you to detach + the contained object at the specified position. A detached object + should eventually be deallocated with operator delete. + Similarly, the attach() function allows you to attach + a new object at the specified position.

+ +

When C++ exceptions are disabled, the push_back(), + insert(), and reserve() functions + return an error code to signal the out of memory condition:

+ +
+namespace xml_schema
+{
+  template <typename T>
+  class var_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (T*);
+
+    error
+    insert (iterator, T*);
+
+    error
+    insert (iterator, T*, iterator& result);
+
+    error
+    reserve (size_t);
+  };
+}
+  
+ + +

When STL is enabled, the string_sequence class has + the same interface as fix_sequence<std::string>. When + STL is disabled and strings are mapped to char*, + string_sequence has a special interface. When C++ + exceptions are enabled, it has the following definition:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    typedef char*         value_type;
+    typedef char**        pointer;
+    typedef const char**  const_pointer;
+    typedef char*         reference;
+    typedef const char*   const_reference;
+
+    typedef size_t        size_type;
+    typedef ptrdiff_t     difference_type;
+
+    typedef char** iterator;
+    typedef const char* const* const_iterator;
+
+    string_sequence ();
+
+    void
+    swap (string_sequence&);
+
+  private:
+    string_sequence (string_sequence&);
+
+    string_sequence&
+    operator= (string_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    char*
+    front ();
+
+    const char*
+    front () const;
+
+    char*
+    back ();
+
+    const char*
+    back () const;
+
+    char*
+    operator[] (size_t);
+
+    const char*
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    push_back (char*);
+
+    void
+    push_back_copy (const char*);
+
+    iterator
+    insert (iterator, char*);
+
+    void
+    reserve (size_t);
+
+    char*
+    detach (iterator);
+
+    void
+    attach (iterator, char*);
+  };
+}
+  
+ +

The push_back() and insert() functions + assume ownership of the passed string which should be allocated + with operator new[] and will be deallocated + with operator delete[] by the string_sequence + object. Similar to var_sequence, these two functions + free the passed string if the reallocation of the underlying + sequence buffer fails. The push_back_copy() + function makes a copy of the passed string. + The string_sequence class also provides the + detach() and attach() functions. + The detach() function allows you to detach + the contained string at the specified position. A detached string + should eventually be deallocated with operator delete[]. + Similarly, the attach() function allows you to attach + a new string at the specified position.

+ +

When C++ exceptions are disabled, the signatures of the + push_back(), push_back_copy(), + insert(), and reserve() functions + in the string_sequence class change as follows:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (char*);
+
+    error
+    push_back_copy (const char*);
+
+    error
+    insert (iterator, char*);
+
+    error
+    insert (iterator, char*, iterator& result);
+
+    error
+    reserve (size_t);
+  };
+}
+  
+ +

4.5 Compositors

+ +

The XML Schema language provides three compositor constructs that + are used to group elements: all, sequence, + and choice. If a compositor has an optional + or sequence cardinality class (see Section + 4.4, "Attributes and Elements") or if a compositor is + inside choice, then the C++/Hybrid mapping generates + a nested class for such a compositor as well as a set of accessor + and modifier functions similar to the ones defined for elements + and attributes. Otherwise, the member functions, corresponding + to elements defined in a compositor, are generated directly in + the containing class.

+ +

Compositor classes are either fixed or variable-length and + obey the same storage and passing rules as object model + classes corresponding to XML Schema types (see Section + 4.2, "Memory Management"). Consider the following schema + fragment as an example:

+ +
+<complexType name="type">
+  <sequence>
+    <sequence minOccurs="0">
+      <element name="a" type="int"/>
+      <element name="b" type="string" maxOccurs="unbounded"/>
+    </sequence>
+    <sequence maxOccurs="unbounded">
+      <element name="c" type="int"/>
+      <element name="d" type="string"/>
+    </sequence>
+  </sequence>
+</complexType>
+  
+ +

The corresponding object model class is shown below:

+ +
+// type (variable-length)
+//
+class type
+{
+public:
+  type ();
+
+private:
+  type (const type&);
+  type& operator= (const type&);
+
+public:
+  // sequence (variable-length)
+  //
+  class sequence_type
+  {
+  public:
+    sequence_type ();
+
+  private:
+    sequence_type (const sequence_type&);
+    sequence_type& operator= (const sequence_type&);
+
+  public:
+    // a
+    //
+    int
+    a () const;
+
+    int&
+    a ();
+
+    void
+    a (int);
+
+    // b
+    //
+    typedef xml_schema::string_sequence b_sequence;
+    typedef b_sequence::iterator b_iterator;
+    typedef b_sequence::const_iterator b_const_iterator;
+
+    const b_sequence&
+    b () const;
+
+    b_sequence&
+    b ();
+
+  private:
+    ...
+  };
+
+  bool
+  sequence_present () const;
+
+  const sequence_type&
+  sequence () const;
+
+  sequence_type&
+  sequence ();
+
+  void
+  sequence (sequence_type*);
+
+  // sequence1 (fixed-length)
+  //
+  class sequence1_type
+  {
+  public:
+    sequence1_type ();
+    sequence1_type (const sequence1_type&);
+    sequence1_type& operator= (const sequence1_type&);
+
+    // c
+    //
+    int
+    c () const;
+
+    int&
+    c ();
+
+    void
+    c (int);
+
+    // d
+    //
+    const std::string&
+    d () const;
+
+    std::string&
+    d ();
+
+    void
+    d (const std::string&);
+
+  private:
+    ...
+  };
+
+  typedef xml_schema::fix_sequence<sequence1_type> sequence1_sequence;
+  typedef sequence1_sequence::iterator sequence1_iterator;
+  typedef sequence1_sequence::const_iterator sequence1_const_iterator;
+
+  const sequence1_sequence&
+  sequence1 () const;
+
+  sequence1_sequence&
+  sequence1 ();
+
+private:
+  ...
+};
+  
+ +

The content of the outer sequence compositor is + generated in-line since this compositor belongs to the one + cardinality class. The first nested sequence compositor + is optional (minOccurs="0"), which results in a corresponding + nested class. Notice that the sequence_type is + variable-length and the accessor and modifier functions corresponding + to this sequence compositor are the same as for an + optional element or attribute. Similarly, the second nested + compositor is of the sequence cardinality class + (maxOccurs="unbounded"), which also results in a + nested class and a set of accessor functions.

+ +

Generated code corresponding to an all and + sequence compositor, whether in-line or as a + nested class, simply define accessor and modifier functions + for the elements that this compositor contains. For the + choice compositor, on the other hand, + additional types and functions are generated to support + querying and selecting the choice arm that is in effect. + Consider the following simple example:

+ +
+<complexType name="type">
+  <choice>
+    <element name="a" type="int"/>
+    <element name="b" type="string"/>
+    <element name="c" type="boolean"/>
+  </choice>
+</complexType>
+  
+ + +

The corresponding object model class is shown next:

+ +
+// type (fixed-length)
+//
+class type
+{
+public:
+  type ();
+  type (const type&);
+  type& operator= (const type&);
+
+  // choice
+  //
+  enum choice_arm_tag
+  {
+    a_tag,
+    b_tag,
+    c_tag
+  };
+
+  choice_arm_tag
+  choice_arm () const;
+
+  void
+  choice_arm (choice_arm_tag);
+
+  // a
+  //
+  int
+  a () const;
+
+  int&
+  a ();
+
+  void
+  a (int);
+
+  // b
+  //
+  const std::string&
+  b () const;
+
+  std::string&
+  b ();
+
+  void
+  b (const std::string&);
+
+  // c
+  //
+  bool
+  c () const;
+
+  bool&
+  c ();
+
+  void
+  c (bool);
+
+private:
+  ...
+};
+  
+ +

The extra type is the choice_arm_tag enumeration + which defines a set of tags corresponding to each choice arm. + There are also the choice_arm() accessor and modifier + functions that can be used to query and set the current choice arm. + The following code fragment shows how we can use this class:

+ +
+type& x = ...
+
+switch (x.choice_arm ())
+{
+case type::a_tag:
+  {
+    cout << "a: " << x.a () << endl;
+    break;
+  }
+case type::b_tag:
+  {
+    cout << "b: " << x.b () << endl;
+    break;
+  }
+case type::c_tag:
+  {
+    cout << "c: " << x.c () << endl;
+    break;
+  }
+}
+
+// Modifiers automatically set the corresponding arm.
+//
+x.a (10);
+
+// For accessors we need to select the arm explicitly.
+//
+x.choice_arm (type::b_tag);
+x.b () = "b";
+  
+ +

The following slightly more complex example triggers the generation of + nested classes for the choice compositor as well as for + the sequence compositor inside choice. + Notice that the nested class for sequence is generated + because it is in choice even though its cardinality + class is one.

+ +
+<complexType name="type">
+  <choice maxOccurs="unbounded">
+    <sequence>
+      <element name="a" type="int"/>
+      <element name="b" type="string"/>
+    </sequence>
+    <element name="c" type="boolean"/>
+  </choice>
+</complexType>
+  
+ +

The corresponding object model class is shown next:

+ +
+// type (variable-length)
+//
+class type
+{
+public:
+  type ();
+
+private:
+  type (const type&);
+  type& operator= (const type&);
+
+public:
+  // choice (fixed-length)
+  //
+  class choice_type
+  {
+  public:
+    choice_type ();
+    choice_type (const choice_type&);
+    choice_type& operator= (const choice_type&);
+
+    enum choice_arm_tag
+    {
+      sequence_tag,
+      c_tag
+    };
+
+    choice_arm_tag
+    choice_arm () const;
+
+    void
+    choice_arm (choice_arm_tag);
+
+    // sequence (fixed-length)
+    //
+    class sequence_type
+    {
+    public:
+      sequence_type ();
+      sequence_type (const sequence_type&);
+      sequence_type& operator= (const sequence_type&);
+
+      // a
+      //
+      int
+      a () const;
+
+      int&
+      a ();
+
+      void
+      a (int);
+
+      // b
+      //
+      const std::string&
+      b () const;
+
+      std::string&
+      b ();
+
+      void
+      b (const std::string&);
+
+    private:
+      ...
+    };
+
+    const sequence_type&
+    sequence () const;
+
+    sequence_type&
+    sequence ();
+
+    void
+    sequence (const sequence_type&);
+
+    // c
+    //
+    bool
+    c () const;
+
+    bool&
+    c ();
+
+    void
+    c (bool);
+
+  private:
+    ...
+  };
+
+  typedef xml_schema::fix_sequence<choice_type> choice_sequence;
+  typedef choice_sequence::iterator choice_iterator;
+  typedef choice_sequence::const_iterator choice_const_iterator;
+
+  const choice_sequence&
+  choice () const;
+
+  choice_sequence&
+  choice ();
+
+private:
+  ...
+};
+  
+ +

4.6 Accessing the Object Model

+ +

In this section we will examine how to get to the information + stored in the object model for the person records vocabulary + introduced at the beginning of this chapter. The following + application accesses and prints the contents of the + people.xml file:

+ +
+#include <memory>
+#include <iostream>
+
+#include "people.hxx"
+#include "people-pimpl.hxx"
+
+using namespace std;
+
+int
+main ()
+{
+  // Parse.
+  //
+  people_paggr people_p;
+  xml_schema::document_pimpl doc_p (people_p.root_parser (),
+                                    people_p.root_name ());
+  people_p.pre ();
+  doc_p.parse ("people.xml");
+  auto_ptr<people> ppl (people_p.post ());
+
+  // Iterate over individual person records.
+  //
+  people::person_sequence& ps = ppl->person ();
+
+  for (people::person_iterator i = ps.begin (); i != ps.end (); ++i)
+  {
+    person& p = *i;
+
+    // Print names: first-name and last-name are required elements,
+    // middle-name is optional.
+    //
+    cout << "name:   " << p.first_name () << " ";
+
+    if (p.middle_name_present ())
+      cout << p.middle_name () << " ";
+
+    cout << p.last_name () << endl;
+
+    // Print gender, age, and id which are all required.
+    //
+    cout << "gender: " << p.gender ().string () << endl
+         << "age:    " << p.age () << endl
+         << "id:     " << p.id () << endl
+         << endl;
+  }
+}
+  
+ +

This code shows common patterns of accessing elements and attributes + with different cardinality classes. For the sequence element + (person in the people type) we first obtain a + reference to the container and then iterate over individual + records. The values of elements and attributes with the + one cardinality class (first-name, + last-name, gender, age, + and id) can be obtained directly by calling the + corresponding accessor functions. For the optional + middle-name element we first check if the value is present + and only then call the corresponding accessor to retrieve it.

+ +

Note that when we want to reduce typing by creating a variable + representing a fragment of the object model that we are currently + working with (ps and p above), we obtain + a reference to that fragment instead of making a copy. This is + generally a good rule to follow when creating efficient + applications.

+ +

If we run the above application on our sample + people.xml, the output looks as follows:

+ +
+name:   John Doe
+gender: male
+age:    32
+id:     1
+
+name:   Jane Mary Doe
+gender: female
+age:    28
+id:     2
+  
+ + +

4.7 Modifying the Object Model

+ +

In this section we will examine how to modify the information + stored in the object model for our person records vocabulary. + The following application changes the contents of the + people.xml file:

+ +
+#include <memory>
+#include <iostream>
+
+#include "people.hxx"
+#include "people-pimpl.hxx"
+#include "people-simpl.hxx"
+
+using namespace std;
+
+int
+main ()
+{
+  // Parse.
+  //
+  people_paggr people_p;
+  xml_schema::document_pimpl doc_p (people_p.root_parser (),
+                                    people_p.root_name ());
+  people_p.pre ();
+  doc_p.parse ("people.xml");
+  auto_ptr<people> ppl (people_p.post ());
+
+  // Iterate over individual person records and increment
+  // the age.
+  //
+  people::person_sequence& ps = ppl->person ();
+
+  for (people::person_iterator i = ps.begin (); i != ps.end (); ++i)
+  {
+    i->age ()++; // Alternative way: i->age (i->age () + 1)
+  }
+
+  // Add middle-name to the first record and remove it from
+  // the second.
+  //
+  person& john = ps[0];
+  person& jane = ps[1];
+
+  john.middle_name ("Mary");
+  jane.middle_name_present (false);
+
+  // Add another John record.
+  //
+  ps.push_back (john);
+
+  // Serialize the modified object model to XML.
+  //
+  people_saggr people_s;
+  xml_schema::document_simpl doc_s (people_s.root_serializer (),
+                                    people_s.root_name ());
+  people_s.pre (*ppl);
+  doc_s.serialize (cout, xml_schema::document_simpl::pretty_print);
+  people_s.post ();
+}
+  
+ +

The first modification the above application performs is iterating + over person records and incrementing the age value. This code + fragment shows how to modify the value of a required attribute + or element. The next modification shows how to set a new value + for the optional middle-name element as well + as clear its value. Finally, the example adds a copy of the + John Doe record to the person element sequence.

+ +

Note that in this case using references for the ps, + john, and jane variables is no longer + a performance improvement but a requirement for the application + to function correctly. If we hadn't used references, all our changes + would have been made on copies without affecting the object model.

+ +

If we run the above application on our sample people.xml, + the output looks as follows:

+ +
+<?xml version="1.0"?>
+<people>
+
+  <person id="1">
+    <first-name>John</first-name>
+    <middle-name>Mary</middle-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>33</age>
+  </person>
+
+  <person id="2">
+    <first-name>Jane</first-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>29</age>
+  </person>
+
+  <person id="1">
+    <first-name>John</first-name>
+    <middle-name>Mary</middle-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>33</age>
+  </person>
+
+</people>
+  
+ +

4.8 Creating the Object Model from Scratch

+ +

In this section we will examine how to create a new object model + for our person records vocabulary. The following application + recreates the content of the original people.xml + file:

+ +
+#include <iostream>
+
+#include "people.hxx"
+#include "people-simpl.hxx"
+
+using namespace std;
+
+int
+main ()
+{
+  people ppl;
+  people::person_sequence& ps = ppl.person ();
+
+  // John
+  //
+  {
+    person p;
+    p.first_name ("John");
+    p.last_name ("Doe");
+    p.gender (gender::male);
+    p.age (32);
+    p.id (1);
+
+    ps.push_back (p);
+  }
+
+  // Jane
+  //
+  {
+    person p;
+    p.first_name ("Jane");
+    p.middle_name ("Mary");
+    p.last_name ("Doe");
+    p.gender (gender::female);
+    p.age (28);
+    p.id (2);
+
+    ps.push_back (p);
+  }
+
+  // Serialize the object model to XML.
+  //
+  people_saggr people_s;
+  xml_schema::document_simpl doc_s (people_s.root_serializer (),
+                                    people_s.root_name ());
+  people_s.pre (ppl);
+  doc_s.serialize (cout, xml_schema::document_simpl::pretty_print);
+  people_s.post ();
+}
+  
+ +

The only new part in the above application is the calls + to the people and person + constructors. As a general rule, a newly created instance + does not assign any values to its elements and attributes. + That is, members with the one cardinality + class are left uninitialized, members with the optional + cardinality class are set to the "not present" state, + and members with the sequence cardinality class + have empty containers. After the instance has been + created, we can set its element and attribute values + using the modifier functions.

+ +

The above application produces the following output:

+ +
+<?xml version="1.0" ?>
+<people>
+
+  <person id="1">
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+
+  <person id="2">
+    <first-name>Jane</first-name>
+    <middle-name>Mary</middle-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+
+</people>
+  
+ +

4.9 Customizing the Object Model

+ +

Sometimes it is desirable to add extra, application-specific + data or functionality to some object model classes or + nested compositor classes. Cases where this may be required + include handling of typeless content matched by XML Schema + wildcards as well as a need for an application to pass extra + data or provide custom functions as part of the object model. + The C++/Hybrid mapping provides two mechanisms for accomplishing + this: custom data and custom types. Custom data is a light-weight + mechanism for storing application-specific data by allowing you + to add a sequence of opaque objects, stored as void*, + to select generated classes. Type customization is a more + powerful mechanism that allows you to provide custom implementations + for select object model classes. You have the option of either extending + the generated version of the class (for example, by adding extra data + members and/or functions) or providing your own implementation from + scratch. The latter approach essentially allows you to change the + mapping of XML Schema to C++ on a case by case basis.

+ +

It is also possible to customize the parsing and serialization code, + for example, to populate the custom data sequence or custom data + members during parsing and later serialize them to XML. See + Section 6.1, "Customizing Parsers and + Serializers" for details. The remainder of this section discusses + the custom data and custom types mechanisms in more detail.

+ +

To instruct the XSD/e compiler to include custom data + in a specific object model class, we need to use the + --custom-data option with the corresponding + XML Schema type name as its argument. To include custom + data into a nested compositor class, use its qualified + name starting with the XML Schema type, for example + type::sequence1. If we would like to + add the ability to store custom data in the generated + person class from our person records + vocabulary, we can compile people.xsd + like this:

+ +
+$ xsde cxx-hybrid --custom-data person people.xsd
+  
+ +

The resulting person class will have the + following extra set of type definitions and functions:

+ + +
+// person (variable-length)
+//
+class person
+{
+public:
+
+  ...
+
+  // Custom data.
+  //
+  typedef xml_schema::data_sequence custom_data_sequence;
+  typedef custom_data_sequence::iterator custom_data_iterator;
+  typedef custom_data_sequence::const_iterator custom_data_const_iterator;
+
+  const custom_data_sequence&
+  custom_data () const;
+
+  custom_data_sequence&
+  custom_data ();
+};
+  
+ +

Notice also that the person class is now variable-length + since it contains a sequence. When C++ exceptions are enabled, the + custom data sequence has the following interface:

+ +
+namespace xml_schema
+{
+  class data_sequence
+  {
+  public:
+    typedef void*         value_type;
+    typedef void**        pointer;
+    typedef const void**  const_pointer;
+    typedef void*         reference;
+    typedef const void*   const_reference;
+
+    typedef size_t        size_type;
+    typedef ptrdiff_t     difference_type;
+
+    typedef void** iterator;
+    typedef const void* const* const_iterator;
+
+    typedef void (*destroy_func) (void* data, size_t pos);
+    typedef void* (*clone_func) (void* data, size_t pos);
+
+  public:
+    data_sequence ();
+
+    void
+    destructor (destroy_func);
+
+    void
+    clone (clone_func);
+
+    void
+    swap (data_sequence&);
+
+  private:
+    data_sequence (const data_sequence&);
+
+    data_sequence&
+    operator= (data_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    void*
+    front ();
+
+    const void*
+    front () const;
+
+    void*
+    back ();
+
+    const void*
+    back () const;
+
+    void*
+    operator[] (size_t);
+
+    const void*
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    push_back (void*);
+
+    iterator
+    insert (iterator, void*);
+
+    void
+    reserve (size_t);
+  };
+}
+  
+ +

The destructor() modifier allows you to specify + the clean up function used to free the sequence elements. + Similarly, the clone() modifier allows you to specify + the cloning function used to copy the sequence elements. + The second argument in these functions is the position + of the element in the sequence. This allows you to store objects + of different types in the same custom + data sequence.

+ +

The push_back() and insert() functions + free the passed object if the reallocation of the underlying + sequence buffer fails. When exceptions are disabled, the + push_back(), + insert(), and reserve() functions + return an error code to signal the out of memory condition:

+ +
+namespace xml_schema
+{
+  class data_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (void*);
+
+    error
+    insert (iterator, void*);
+
+    error
+    insert (iterator, void*, iterator& result);
+
+    error
+    reserve (size_t);
+  };
+}
+  
+ +

The following code fragment shows how we can store and retrieve + custom data in the person class:

+ +
+class data
+{
+  ...
+};
+
+void
+destroy_data (void* p, size_t)
+{
+  delete static_cast<data*> (p);
+}
+
+person& = ...;
+person::custom_data_sequence& cd = p.custom_data ();
+
+cd.destructor (&destroy_data);
+
+// Store.
+//
+data* d = new data;
+cd.push_back (d);
+
+// Retrieve.
+//
+for (person::custom_data_iterator i = cd.begin (); i != cd.end (); ++i)
+{
+  data* d = static_cast<data*> (*i);
+}
+  
+ +

To instruct the XSD/e compiler to use a custom implementation + for a specific object model class, we need to use the + --custom-type option. The argument format for this + option is name[=[flags][/[type][/[base][/include]]]]. + The name component is the XML Schema type name being + customized. Optional flags allow you to specify whether + the custom class is fixed or variable-length since customization can + alter this property, normally from fixed-length to + variable-length. The f flag indicates the type is + fixed-length and the v flag indicates the type is + variable-length. If omitted, the default rules are used to determine + the type length (see Section 4.2, "Memory Management"). + + Optional type is a C++ type name, potentially qualified, + that should be used as a custom implementation. If specified, the + object model type is defined as a typedef alias for + this C++ type. Optional base is a C++ name that should + be given to the generated version. It is normally used as a base for + the custom implementation. Optional include is the header + file that defines the custom implementation. It is #include'ed + into the generated code immediately after (if base is + specified) or instead of the generated version. The following + examples show how we can use this option:

+ +
+--custom-type foo
+--custom-type foo=///foo.hxx
+--custom-type foo=v///foo.hxx
+--custom-type foo=f/int
+--custom-type foo=//foo_base/my/foo.hxx
+--custom-type foo=v/wrapper<foo_base>/foo_base
+  
+ +

The first version instructs the XSD/e compiler not to generate + the object model class for the foo XML Schema + type. The generated code simply forward-declares foo + as a class and leaves it to you to provide the implementation. + + The second version is similar to the first, except now we specify + the header file which defines the custom implementation. + This file is automatically included into the generated header + file instead of the standard implementation. + + The third version is similar to the second, except now we specify + that the foo type is variable-length. In the previous + two cases the type length was determined automatically based on the + type definition in the schema. + + In the fourth version we specify that schema type foo + is fixed-length and should be mapped to int. + + The fifth version instructs the XSD/e compiler to generate + the object model class for type foo but call it + foo_base. It also tells the compiler to generate + the #include directive with the my/foo.hxx + file (which presumably defines foo) right after the + foo_base class. + + Finally, the last version specifies that schema type foo + is variable-length and should be mapped to wrapper<foo_base>. + The compiler is also instructed to generate the standard object + model class for type foo but call it foo_base. + + If you omit the last component (include), as in the + final version, then you can provide the custom type definitions using + one of the prologue or epilogue XSD/e compiler options. See the + XSD/e + Compiler Command Line Manual for details.

+ +

Note also that if the type length you specified with the + --custom-type option differs from the default type + length that would have been determined by the XSD/e compiler, + then you need to specify this --custom-type option + when compiling every schema file that includes or imports the + schema that defines the type being customized.

+ +

As an example, let us add a flag to the person class + from our person records vocabulary. This flag can be used by the + application to keep track of whether a particular person record + has been verified. To customize the person type we + can compile people.xsd like this:

+ +
+$ xsde cxx-hybrid --custom-type person=//person_base/person.hxx \
+people.xsd
+  
+ +

The relevant code fragment from the generated header file + looks like this:

+ +
+// person_base (fixed-length)
+//
+class person_base
+{
+  ...
+};
+
+#include "person.hxx"
+
+// people (variable-length)
+//
+class people
+{
+  ...
+
+  // person
+  //
+  typedef xml_schema::fix_sequence<person> person_sequence;
+  typedef person_sequence::iterator person_iterator;
+  typedef person_sequence::const_iterator person_const_iterator;
+
+  const person_sequence&
+  person () const;
+
+  person_sequence&
+  person ();
+
+private:
+  ...
+};
+  
+ +

We base our custom implementation of the person + class on generated person_base and save it to + person.hxx:

+ +
+class person: public person_base
+{
+public:
+  person ()
+    : verified_ (false)
+  {
+  }
+
+  bool
+  verified () const
+  {
+    return verified_;
+  }
+
+  void
+  verified (bool v)
+  {
+    verified_ = v;
+  }
+
+private:
+  bool verified_;
+};
+  
+ +

The client code can use our custom implementation as if the + flag was part of the vocabulary:

+ +
+people::person_sequence& ps = ...;
+
+for (people::person_iterator i = ps.begin (); i != ps.end (); ++i)
+{
+  if (!i->verified ())
+  {
+    // Verify the record.
+
+    ...
+
+    i->verified (true);
+  }
+}
+  
+ + +

4.10 Polymorphic Object Models

+ +

When generating polymorphism-aware code (see Section + 3.7, "Support for Polymorphism"), some objects + in the resulting object model will be polymorphic. By polymorphic + we mean that the object's (static) type as specified in the + object model's interface may differ from the object's actual + (dynamic) type. Because of this, it may be necessary to discover + the object's actual type at runtime and cast it to this type to + gain access to the object's extended interface. Consider the + following schema as an example:

+ +
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="person">
+    <xs:sequence>
+      <xs:element name="name" type="xs:string"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <!-- substitution group root -->
+  <xs:element name="person" type="person"/>
+
+  <xs:complexType name="superman">
+    <xs:complexContent>
+      <xs:extension base="person">
+        <xs:attribute name="can-fly" type="xs:boolean"/>
+      </xs:extension>
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:element name="superman"
+              type="superman"
+              substitutionGroup="person"/>
+
+  <xs:complexType name="batman">
+    <xs:complexContent>
+      <xs:extension base="superman">
+        <xs:attribute name="wing-span" type="xs:unsignedInt"/>
+      </xs:extension>
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:element name="batman"
+              type="batman"
+              substitutionGroup="superman"/>
+
+  <xs:complexType name="supermen">
+    <xs:sequence>
+      <xs:element ref="person" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="supermen" type="supermen"/>
+
+</xs:schema>
+  
+ +

Conforming XML documents can use the superman + and batman types in place of the person + type either by specifying the type with the xsi:type + attributes or by using the elements from the substitution + group, for instance:

+ + +
+<supermen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+
+  <person>
+    <name>John Doe</name>
+  </person>
+
+  <superman can-fly="false">
+    <name>James "007" Bond</name>
+  </superman>
+
+  <superman can-fly="true" wing-span="10" xsi:type="batman">
+    <name>Bruce Wayne</name>
+  </superman>
+
+</supermen>
+  
+ +

When compiling the schema above with the + --generate-polymorphic option, the XSD/e compiler + automatically detects that the type hierarchy starting with + the person type is polymorphic. A polymorphic + type is always variable-length which means objects of polymorphic + types are allocated dynamically and are stored and passed around + as pointers or references. A polymorphic type also defines a + virtual _clone() function (see Section 4.2, + "Memory Management") and a virtual destructor + which allow you to copy and delete an instance of a + polymorphic type via a pointer to its base. The following code + fragment shows how we can parse, access, modify, and serialize + the above XML document:

+ +
+// Parse.
+//
+supermen_paggr supermen_p;
+
+// The last argument to the document's constructor indicates that we
+// are parsing polymorphic XML documents.
+//
+xml_schema::document_pimpl doc_p (
+  supermen_p.root_parser (),
+  supermen_p.root_name (),
+  true);
+
+supermen_p.pre ();
+doc_p.parse ("supermen.xml");
+auto_ptr<supermen> sm (supermen_p.post ());
+
+// Print what we've got.
+//
+for (supermen::person_iterator i = sm->person ().begin ();
+     i != sm->person ().end ();
+     ++i)
+{
+  person& p = *i;
+
+  if (batman* b = dynamic_cast<batman*> (&p))
+  {
+    cerr << b->name () << ", batman, wing span " <<
+      b->wing_span () << endl;
+  }
+  else if (superman* s = dynamic_cast<superman*> (&p))
+  {
+    cerr << s->name () << ", ";
+
+    if (s->can_fly ())
+      cerr << "flying ";
+
+    cerr << "superman" << endl;
+  }
+  else
+  {
+    cerr << p.name () << ", ordinary person" << endl;
+  }
+}
+
+// Add another superman entry.
+//
+auto_ptr<superman> s (new superman);
+s->name ("Clark Kent");
+s->can_fly (true);
+sm->person ().push_back (s.release ());
+
+// Serialize.
+//
+supermen_saggr supermen_s;
+
+// The last argument to the document's constructor indicates that we
+// are serializing polymorphic XML documents.
+//
+xml_schema::document_simpl doc_s (
+  supermen_s.root_serializer (),
+  supermen_s.root_name (),
+  true);
+
+doc_s.add_no_namespace_schema ("supermen.xsd");
+
+supermen_s.pre (*sm);
+doc_s.serialize (cout, xml_schema::document_simpl::pretty_print);
+supermen_s.post ();
+  
+ +

In the example above we used the standard C++ RTTI mechanism + to detect the object's actual (dynamic) type. If RTTI is not + available on your platform, then you can request the generation + of custom runtime type information for polymorphic types + with the --generate-typeinfo XSD/e compiler + option. When this option is specified, each polymorphic + type provides the following two public functions:

+ +
+virtual const std::string&
+_dynamic_type () const;
+
+static const std::string&
+_static_type ();
+  
+ +

Or, if STL is disabled (Section 3.1, "Standard Template + Library"), the following two functions:

+ +
+virtual const char*
+_dynamic_type () const;
+
+static const char*
+_static_type ();
+  
+ +

The _dynamic_type() function returns the object's + dynamic type id. The _static_type() function + returns the type's static id that can be compared to the + dynamic id. The following code fragment shows how + we can change the previous example to use custom type information + instead of C++ RTTI:

+ +
+for (supermen::person_iterator i = sm->person ().begin ();
+     i != sm->person ().end ();
+     ++i)
+{
+  person& p = *i;
+  const string& dt = p._dynamic_type ();
+
+  if (dt == batman::_static_type ())
+  {
+    batman& b = static_cast<batman&> (p)
+    cerr << b.name () << ", batman, wing span " <<
+      b.wing_span () << endl;
+  }
+  else if (dt == superman::_static_type ())
+  {
+    superman& s = static_cast<superman&> (p)
+    cerr << s.name () << ", ";
+
+    if (s.can_fly ())
+      cerr << "flying ";
+
+    cerr << "superman" << endl;
+  }
+  else
+  {
+    cerr << p.name () << ", ordinary person" << endl;
+  }
+}
+  
+ +

Most of the code presented in this section is taken from the + polymorphism example which can be found in the + examples/cxx/hybrid/ directory of the XSD/e distribution. + Handling of xsi:type and substitution groups when used + on root elements requires a number of special actions as shown in + the polyroot example.

+ + + + + +

5 Mapping for Built-In XML Schema Types

+ +

In XML Schema, built-in types, such as int, + string, etc., are defined in the XML Schema namespace. + By default this namespace is mapped to C++ namespace + xml_schema (this mapping can be altered + with the --namespace-map option). The following table + summarizes the mapping of XML Schema built-in types to C++ types + in the C++/Hybrid mapping. Declarations for these types are + automatically included into each generated header file.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XML Schema typeAlias in the xml_schema namespaceC++ type
fixed-length integral types
bytebytesigned char
unsignedByteunsigned_byteunsigned char
shortshort_short
unsignedShortunsigned_shortunsigned short
intint_int
unsignedIntunsigned_intunsigned int
longlong_long or
long long
+ Section 3.5, "64-bit Integer Type"
unsignedLongunsigned_longunsigned long or + unsigned long long
+ Section 3.5, "64-bit Integer Type"
arbitrary-length integral types
integerintegerlong
nonPositiveIntegernon_positive_integerlong
nonNegativeIntegernon_negative_integerunsigned long
positiveIntegerpositive_integerunsigned long
negativeIntegernegative_integerlong
boolean types
booleanbooleanbool
fixed-precision floating-point types
floatfloat_float
doubledouble_double
arbitrary-precision floating-point types
decimaldecimaldouble
string types
stringstringstd::string or char*
+ Section 3.1, "Standard Template Library"
normalizedStringnormalized_stringstd::string or char*
+ Section 3.1, "Standard Template Library"
tokentokenstd::string or char*
+ Section 3.1, "Standard Template Library"
Namenamestd::string or char*
+ Section 3.1, "Standard Template Library"
NMTOKENnmtokenstd::string or char*
+ Section 3.1, "Standard Template Library"
NMTOKENSnmtokensSection 5.2, "Mapping for NMTOKENS and IDREFS"
NCNamencnamestd::string or char*
+ Section 3.1, "Standard Template Library"
languagelanguagestd::string or char*
+ Section 3.1, "Standard Template Library"
qualified name
QNameqnameSection 5.1, "Mapping for QName"
ID/IDREF types
IDidstd::string or char*
+ Section 3.1, "Standard Template Library"
IDREFidrefstd::string or char*
+ Section 3.1, "Standard Template Library"
IDREFSidrefsSection 5.2, "Mapping for NMTOKENS and IDREFS"
URI types
anyURIuristd::string or char*
+ Section 3.1, "Standard Template Library"
binary types
base64Binarybase64_binarySection 5.3, "Mapping for base64Binary and hexBinary"
hexBinaryhex_binarySection 5.3, "Mapping for base64Binary and hexBinary"
date/time types
datedateSection 5.5, "Mapping for date"
dateTimedate_timeSection 5.6, "Mapping for dateTime"
durationdurationSection 5.7, "Mapping for duration"
gDaygdaySection 5.8, "Mapping for gDay"
gMonthgmonthSection 5.9, "Mapping for gMonth"
gMonthDaygmonth_daySection 5.10, "Mapping for gMonthDay"
gYeargyearSection 5.11, "Mapping for gYear"
gYearMonthgyear_monthSection 5.12, "Mapping for gYearMonth"
timetimeSection 5.13, "Mapping for time"
anyType and anySimpleType
anyTypeany_typeSection 5.14, "Mapping for anyType"
anySimpleTypeany_simple_typestd::string or char*
+ Section 3.1, "Standard Template Library"
+ +

As you can see from the table above a number of built-in + XML Schema types are mapped to fundamental C++ types such + as int or bool. All string-based + XML Schema types are mapped to either std::string + or char*, depending on whether the use of STL is + enabled or not. A number of built-in types, such as + QName, the binary types, and the date/time types, + do not have suitable fundamental or standard C++ types to map to. + These types are implemented from scratch in the XSD/e runtime + and are discussed in more detail in the subsequent sections.

+ +

In cases where the schema calls for an inheritance from a built-in + type which is mapped to a fundamental C++ type, a special base + type corresponding to the fundamental type and defined in the + xml_schema namespace is used (C++ does not allow + inheritance from fundamental types). For example:

+ +
+<complexType name="measure">
+  <simpleContent>
+    <extension base="int">
+      <attribute name="unit" type="string" use="required"/>
+    </extension>
+  </simpleContent>
+</complexType>
+  
+ +

The corresponding object model class is shown below:

+ +
+// measure (fixed-length)
+//
+class measure: public xml_schema::int_base
+{
+public:
+  measure ();
+  measure (const measure&);
+  measure& operator= (const measure&);
+
+  // unit
+  //
+  const std::string&
+  unit () const;
+
+  std::string&
+  unit ();
+
+  void
+  unit (const std::string&);
+
+private:
+  ...
+};
+  
+ +

The xml_schema::int_base class has the following + interface:

+ +
+namespace xml_schema
+{
+  class int_base
+  {
+  public:
+    int_base ();
+
+    int_base&
+    operator= (int);
+
+  public:
+    int
+    base_value () const;
+
+    int&
+    base_value ();
+
+    void
+    base_value (int);
+
+    operator const int& () const;
+    operator int& ();
+  };
+}
+  
+ +

All other base types for fundamental C++ types have similar + interfaces. The only exception is the base type for string + types when STL is disabled:

+ +
+namespace xml_schema
+{
+  class string_base
+  {
+  public:
+    string_base ();
+
+    string_base&
+    operator= (char* x)
+
+  public:
+    const char*
+    base_value () const;
+
+    char*
+    base_value ();
+
+    void
+    base_value (char* x);
+
+    char*
+    base_value_detach ();
+
+    operator const char* () const;
+    operator char* ();
+  };
+}
+  
+ +

Note that the string_base object assumes ownership + of the strings passed to the assignment operator and the + base_value() modifier. If you detach the + string value then it should eventually be deallocated with + operator delete[].

+ +

5.1 Mapping for QName

+ +

The QName built-in XML Schema type is mapped to the + qname class which represents an XML qualified name. + With STL enabled (Section 3.1, "Standard Template + Library"), it has the following interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (const std::string& name);
+    qname (const std::string& prefix, const std::string& name);
+
+    void
+    swap (qname&);
+
+    const std::string&
+    prefix () const;
+
+    std::string&
+    prefix ();
+
+    void
+    prefix (const std::string&);
+
+    const std::string&
+    name () const;
+
+    std::string&
+    name ();
+
+    void
+    name (const std::string&);
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+  
+ +

When STL is disabled and C++ exceptions are enabled + (Section 3.3, "C++ Exceptions"), the + qname type has the following interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (char* name);
+    qname (char* prefix, char* name);
+
+    void
+    swap (qname&);
+
+  private:
+    qname (const qname&);
+
+    qname&
+    operator= (const qname&);
+
+  public:
+    char*
+    prefix ();
+
+    const char*
+    prefix () const;
+
+    void
+    prefix (char*);
+
+    void
+    prefix_copy (const char*);
+
+    char*
+    prefix_detach ();
+
+  public:
+    char*
+    name ();
+
+    const char*
+    name () const;
+
+    void
+    name (char*);
+
+    void
+    name_copy (const char*);
+
+    char*
+    name_detach ();
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+
+ +

The modifier functions and constructors that have the char* + argument assume ownership of the passed strings which should be allocated + with operator new char[] and will be deallocated with + operator delete[] by the qname object. + If you detach the underlying prefix or name strings, then they + should eventually be deallocated with operator delete[]. +

+ +

Finally, if both STL and C++ exceptions are disabled, the + qname type has the following interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (char* name);
+    qname (char* prefix, char* name);
+
+    void
+    swap (qname&);
+
+  private:
+    qname (const qname&);
+
+    qname&
+    operator= (const qname&);
+
+  public:
+    char*
+    prefix ();
+
+    const char*
+    prefix () const;
+
+    void
+    prefix (char*);
+
+    error
+    prefix_copy (const char*);
+
+    char*
+    prefix_detach ();
+
+  public:
+    char*
+    name ();
+
+    const char*
+    name () const;
+
+    void
+    name (char*);
+
+    error
+    name_copy (const char*);
+
+    char*
+    name_detach ();
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+  
+ +

5.2 Mapping for NMTOKENS and IDREFS

+ +

The NMTOKENS and IDREFS built-in + XML Schema types are mapped to the string sequence type which + is discussed in Section 4.4, "Attributes and + Elements".

+ +

5.3 Mapping for base64Binary and hexBinary

+ +

The base64Binary and hexBinary built-in + XML Schema types are mapped to the buffer class. + With C++ exceptions enabled (Section 3.3, "C++ + Exceptions"), it has the following interface:

+ +
+namespace xml_schema
+{
+  class buffer
+  {
+  public:
+    class bounds {}; // Out of bounds exception.
+
+  public:
+    buffer ();
+
+    explicit
+    buffer (size_t size);
+    buffer (size_t size, size_t capacity);
+    buffer (const void* data, size_t size);
+    buffer (const void* data, size_t size, size_t capacity);
+
+    enum ownership_value { assume_ownership };
+
+    // This constructor assumes ownership of the memory passed.
+    //
+    buffer (void* data, size_t size, size_t capacity, ownership_value);
+
+  private:
+    buffer (const buffer&);
+
+    buffer&
+    operator= (const buffer&);
+
+  public:
+    void
+    assign (void* data, size_t size);
+
+    void
+    attach (void* data, size_t size, size_t capacity);
+
+    void*
+    detach ();
+
+
+    void
+    swap (buffer&);
+
+  public:
+    size_t
+    capacity () const;
+
+    bool
+    capacity (size_t);
+
+  public:
+    size_t
+    size () const;
+
+    bool
+    size (size_t);
+
+  public:
+    const char*
+    data () const;
+
+    char*
+    data ();
+
+    const char*
+    begin () const;
+
+    char*
+    begin ();
+
+    const char*
+    end () const;
+
+    char*
+    end ();
+  };
+
+  bool
+  operator== (const buffer&, const buffer&);
+
+  bool
+  operator!= (const buffer&, const buffer&);
+}
+  
+ +

The last constructor and the attach() member function + make the buffer instance assume the ownership of the + memory block pointed to by the data argument and + eventually release it by calling operator delete(). + The detach() member function detaches and returns the + underlying memory block which should eventually be released by + calling operator delete(). +

+ +

The capacity() and size() modifier functions + return true if the underlying buffer has moved. The + bounds exception is thrown if the constructor or + attach() member function arguments violate the + (size <= capacity) constraint.

+ +

If C++ exceptions are disabled, the buffer class has + the following interface:

+ +
+namespace xml_schema
+{
+  class buffer
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_bounds,
+      error_no_memory
+    };
+
+    buffer ();
+
+  private:
+    buffer (const buffer&);
+
+    buffer&
+    operator= (const buffer&);
+
+  public:
+    error
+    assign (void* data, size_t size);
+
+    error
+    attach (void* data, size_t size, size_t capacity);
+
+    void*
+    detach ();
+
+    void
+    swap (buffer&);
+
+  public:
+    size_t
+    capacity () const;
+
+    error
+    capacity (size_t);
+
+    error
+    capacity (size_t, bool& moved);
+
+  public:
+    size_t
+    size () const;
+
+    error
+    size (size_t);
+
+    error
+    size (size_t, bool& moved);
+
+  public:
+    const char*
+    data () const;
+
+    char*
+    data ();
+
+    const char*
+    begin () const;
+
+    char*
+    begin ();
+
+    const char*
+    end () const;
+
+    char*
+    end ();
+  };
+
+  bool
+  operator== (const buffer&, const buffer&);
+
+  bool
+  operator!= (const buffer&, const buffer&);
+}
+  
+ +

5.4 Time Zone Representation

+ +

The date, dateTime, gDay, + gMonth, gMonthDay, gYear, + gYearMonth, and time XML Schema built-in + types all include an optional time zone component. The following + time_zone base class is used to represent this + information:

+ +
+namespace xml_schema
+{
+  class time_zone
+  {
+  public:
+    time_zone ();
+    time_zone (short hours, short minutes);
+
+    bool
+    zone_present () const;
+
+    void
+    zone_reset ();
+
+    short
+    zone_hours () const;
+
+    void
+    zone_hours (short);
+
+    short
+    zone_minutes () const;
+
+    void
+    zone_minutes (short);
+  };
+
+  bool
+  operator== (const time_zone&, const time_zone&);
+
+  bool
+  operator!= (const time_zone&, const time_zone&);
+}
+  
+ +

The zone_present() accessor function returns true + if the time zone is specified. The zone_reset() modifier + function resets the time zone object to the "not specified" + state. If the time zone offset is negative then both hours and + minutes components should be negative.

+ +

5.5 Mapping for date

+ +

The date built-in XML Schema type is mapped to the + date class which represents a year, a day, and a month + with an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 5.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class date: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    date ();
+
+    date (int year, unsigned short month, unsigned short day);
+
+    date (int year, unsigned short month, unsigned short day,
+          short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const date&, const date&);
+
+  bool
+  operator!= (const date&, const date&);
+}
+  
+ +

5.6 Mapping for dateTime

+ +

The dateTime built-in XML Schema type is mapped to the + date_time class which represents a year, a month, a day, + hours, minutes, and seconds with an optional time zone. Its interface + is presented below. For more information on the base + xml_schema::time_zone class refer to Section + 5.4, "Time Zone Representation".

+ +
+namespace xml_schema
+{
+  class date_time: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    date_time ();
+
+    date_time (int year, unsigned short month, unsigned short day,
+               unsigned short hours, unsigned short minutes,
+               double seconds);
+
+    date_time (int year, unsigned short month, unsigned short day,
+               unsigned short hours, unsigned short minutes,
+               double seconds, short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+
+    unsigned short
+    hours () const;
+
+    void
+    hours (unsigned short);
+
+    unsigned short
+    minutes () const;
+
+    void
+    minutes (unsigned short);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const date_time&, const date_time&);
+
+  bool
+  operator!= (const date_time&, const date_time&);
+}
+  
+ +

5.7 Mapping for duration

+ +

The duration built-in XML Schema type is mapped to the + duration class which represents a potentially + negative duration in the form of years, months, days, hours, minutes, + and seconds. Its interface is presented below.

+ +
+namespace xml_schema
+{
+  class duration
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    duration ();
+
+    duration (bool negative,
+              unsigned int years, unsigned int months, unsigned int days,
+              unsigned int hours, unsigned int minutes, double seconds);
+
+    bool
+    negative () const;
+
+    void
+    negative (bool);
+
+    unsigned int
+    years () const;
+
+    void
+    years (unsigned int);
+
+    unsigned int
+    months () const;
+
+    void
+    months (unsigned int);
+
+    unsigned int
+    days () const;
+
+    void
+    days (unsigned int);
+
+    unsigned int
+    hours () const;
+
+    void
+    hours (unsigned int);
+
+    unsigned int
+    minutes () const;
+
+    void
+    minutes (unsigned int);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const duration&, const duration&);
+
+  bool
+  operator!= (const duration&, const duration&);
+}
+  
+ + +

5.8 Mapping for gDay

+ +

The gDay built-in XML Schema type is mapped to the + gday class which represents a day of the month with + an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 5.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gday: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gday ();
+
+    explicit
+    gday (unsigned short day);
+
+    gday (unsigned short day, short zone_hours, short zone_minutes);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const gday&, const gday&);
+
+  bool
+  operator!= (const gday&, const gday&);
+}
+  
+ +

5.9 Mapping for gMonth

+ +

The gMonth built-in XML Schema type is mapped to the + gmonth class which represents a month of the year + with an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 5.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gmonth: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gmonth ();
+
+    explicit
+    gmonth (unsigned short month);
+
+    gmonth (unsigned short month,
+            short zone_hours, short zone_minutes);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+  };
+
+  bool
+  operator== (const gmonth&, const gmonth&);
+
+  bool
+  operator!= (const gmonth&, const gmonth&);
+}
+  
+ +

5.10 Mapping for gMonthDay

+ +

The gMonthDay built-in XML Schema type is mapped to the + gmonth_day class which represents a day and a month of + the year with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 5.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gmonth_day: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gmonth_day ();
+
+    gmonth_day (unsigned short month, unsigned short day);
+
+    gmonth_day (unsigned short month, unsigned short day,
+                short zone_hours, short zone_minutes);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const gmonth_day&, const gmonth_day&);
+
+  bool
+  operator!= (const gmonth_day&, const gmonth_day&);
+}
+  
+ +

5.11 Mapping for gYear

+ +

The gYear built-in XML Schema type is mapped to the + gyear class which represents a year with + an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 5.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gyear: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gyear ();
+
+    explicit
+    gyear (int year);
+
+    gyear (int year, short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+  };
+
+  bool
+  operator== (const gyear&, const gyear&);
+
+  bool
+  operator!= (const gyear&, const gyear&);
+}
+  
+ +

5.12 Mapping for gYearMonth

+ +

The gYearMonth built-in XML Schema type is mapped to the + gyear_month class which represents a year and a month + with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 5.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gyear_month: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gyear_month ();
+
+    gyear_month (int year, unsigned short month);
+
+    gyear_month (int year, unsigned short month,
+                 short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+  };
+
+  bool
+  operator== (const gyear_month&, const gyear_month&);
+
+  bool
+  operator!= (const gyear_month&, const gyear_month&);
+}
+  
+ + +

5.13 Mapping for time

+ +

The time built-in XML Schema type is mapped to the + time class which represents hours, minutes, + and seconds with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 5.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class time: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    time ();
+
+    time (unsigned short hours, unsigned short minutes, double seconds);
+
+    time (unsigned short hours, unsigned short minutes, double seconds,
+          short zone_hours, short zone_minutes);
+
+    unsigned short
+    hours () const;
+
+    void
+    hours (unsigned short);
+
+    unsigned short
+    minutes () const;
+
+    void
+    minutes (unsigned short);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const time&, const time&);
+
+  bool
+  operator!= (const time&, const time&);
+}
+  
+ +

5.14 Mapping for anyType

+ +

The anyType built-in XML Schema type is mapped to + the any_type class in the xml_schema + namespace. With C++ exceptions enabled (Section 3.3, + "C++ Exceptions"), it has the following interface:

+ +
+namespace xml_schema
+{
+  class any_type
+  {
+  public:
+    // Custom data.
+    //
+    typedef xml_schema::data_sequence custom_data_sequence;
+    typedef custom_data_sequence::iterator custom_data_iterator;
+    typedef custom_data_sequence::const_iterator custom_data_const_iterator;
+
+    void
+    allocate_custom_data ();
+
+    const custom_data_sequence&
+    custom_data () const;
+
+    custom_data_sequence&
+    custom_data ();
+  };
+}
+  
+ +

If C++ exceptions are disabled, the any_type class has + the following interface:

+ +
+namespace xml_schema
+{
+  class any_type
+  {
+  public:
+    // Custom data.
+    //
+    typedef xml_schema::data_sequence custom_data_sequence;
+    typedef custom_data_sequence::iterator custom_data_iterator;
+    typedef custom_data_sequence::const_iterator custom_data_const_iterator;
+
+    bool
+    allocate_custom_data ();
+
+    const custom_data_sequence&
+    custom_data () const;
+
+    custom_data_sequence&
+    custom_data ();
+  };
+}
+  
+ +

The allocate_custom_data() function allocates the + custom data sequence. With C++ exceptions disabled, it returns + false if memory allocation has failed and true + otherwise. For more information on custom data, refer to + Section 4.9, "Customizing the Object Model".

+ +

The default parser and serializer implementations for the + anyType built-in type ignore all its content and + return an empty any_type instance. If your application + needs to access this content, then you will need to provide your + own implementations of these parser and serializer and use the + custom data sequence to store the extracted data.

+ + + +

6 Parsing and Serialization

+ +

As was mentioned in the introduction, the C++/Hybrid mapping + uses the C++/Parser and C++/Serializer mappings for XML parsing + and serialization. If your parsing and serialization requirements + are fairly basic, for example, parsing from and serializing to + a file or a memory buffer, then you don't need to concern yourself + with these two underlying mappings. On the other hand, the C++/Parser + and C++/Serializer mappings provide well-defined APIs which allow + a great amount of flexibility that may be useful in certain situations. + In such cases, you may need to get an understanding of how the + C++/Parser and C++/Serializer mappings work. See the + Embedded + C++/Parser Mapping Getting Started Guide and the + Embedded + C++/Serializer Mapping Getting Started Guide for more detailed + information on these mappings.

+ +

For each type defined in XML Schema, the C++/Parser and + C++/Serializer mappings generate a parser skeleton class and + serializer skeleton class, respectively. These classes manage + parsing/serialization state, convert data between text + and C++ types, and perform XML Schema validation, if enabled. + Parser skeletons deliver the parsed data and serializer + skeletons request the data to be serialized with callbacks. + These callbacks are implemented by parser and serializer + implementation classes that are derived from the skeletons. + If the application uses the C++/Parser and C++/Serializer + mappings directly, these implementation classes are normally + written by the application developer to perform some + application-specific actions. In case of the C++/Hybrid mapping, + these implementations are automatically generated by the XSD/e + compiler to parse XML to object models and to serialize object + models to XML. + To request the generation of parser skeletons and + implementations, you need to specify the --generate-parser + XSD/e command line option. Similarly, to generate serializer + skeletons and implementations, you will need to use the + --generate-serializer option.

+ +

Before an XML document can be parsed or serialized, the + individual parser and serializer implementations need to + be instantiated and connected to each other. Again, if the + application uses the C++/Parser and C++/Serializer mappings + directly, this is done by the application developer. While + you can also do this with the generated C++/Hybrid parser and + serializer implementations, it is easier to request the + generation of parser and serializer aggregate classes with + the --generate-aggregate options. Aggregate + classes instantiate and connect all the necessary individual + parser and serializer implementations for a particular root + element or type. Consider again the hello.xsd + schema from Chapter 2, "Hello World Example":

+ +
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="hello">
+    <xs:sequence>
+      <xs:element name="greeting" type="xs:string"/>
+      <xs:element name="name" type="xs:string" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="hello" type="hello"/>
+
+</xs:schema>
+  
+ +

If we compile this schema with the --generate-parser, + --generate-serializer, and --generate-aggregate + options, we will have two aggregate classes, hello_paggr + and hello_saggr, generated for the root hello + element. The interface of the hello_paggr class is + presented below:

+ +
+class hello_paggr
+{
+public:
+  hello_paggr ();
+
+  void
+  pre ();
+
+  hello*
+  post ();
+
+  hello_pimpl&
+  root_parser ();
+
+  static const char*
+  root_name ();
+
+  static const char*
+  root_namespace ();
+};
+  
+ +

The pre() and post() functions + call the corresponding callbacks on the root parser + implementation. The root_parser() function + returns the root parser implementation. The root_name() + and root_namespace() functions return the + root element name and namespace, respectively.

+ +

As was shown in Chapter 2, "Hello World Example", + we can use this parser aggregate to create the document parser + (supplied by the C++/Parser mapping) and perform the parsing:

+ +
+hello_paggr hello_p;
+xml_schema::document_pimpl doc_p (hello_p.root_parser (),
+                                  hello_p.root_name ());
+hello_p.pre ();
+doc_p.parse ("hello.xml");
+hello* h = hello_p.post ();
+  
+ +

For more information on the document_pimpl class, + including the other variants of the parse() function + as well as error handling during parsing, see + Chapter 7, + "Document Parser and Error Handling" in the Embedded C++/Parser + Mapping Getting Started Guide.

+ +

The interface of the hello_saggr serializer aggregate + mirrors that of hello_paggr and is presented below:

+ +
+class hello_saggr
+{
+public:
+  hello_saggr ();
+
+  void
+  pre (const hello&);
+
+  void
+  post ();
+
+  hello_simpl&
+  root_serializer ();
+
+  static const char*
+  root_name ();
+
+  static const char*
+  root_namespace ();
+};
+  
+ +

The pre() and post() functions + call the corresponding callbacks on the root serializer + implementation. The root_serializer() function + returns the root serializer implementation. The + root_name() and root_namespace() + functions return the root element name and namespace, + respectively.

+ +

As was shown in Chapter 2, "Hello World Example", + we can use this serializer aggregate to create the document + serializer (supplied by the C++/Serializer mapping) and perform + the serialization:

+ +
+hello_saggr hello_s;
+xml_schema::document_simpl doc_s (hello_s.root_serializer (),
+                                  hello_s.root_name ());
+hello_s.pre (*h);
+doc_s.serialize (std::cout, xml_schema::document_simpl::pretty_print);
+hello_s.post ();
+  
+ +

For more information on the document_simpl class, + including the other variants of the serialize() + function as well as error handling during serialization, see + Chapter 8, + "Document Serializer and Error Handling" in the Embedded + C++/Serializer Mapping Getting Started Guide.

+ +

6.1 Customizing Parsers and Serializers

+ +

The C++/Hybrid mapping allows you to customize the generated + parser and serializer implementations. This mechanism can be + used, for example, to implement filtering, partially + event-driven XML processing, as well as parsing of content + matched by XML Schema wildcards. Filtering allows only parts + of the XML document to be parsed into the object model or only + parts of the object model to be serialized to XML. With + partially event-driven parsing and serialization, we can + process parts of the document as they become available as + well as handle documents that are too large to fit into + memory. This section expects you to have an understanding + of the C++/Parser and C++/Serializer programming models.

+ +

To request customization of a parser or serializer + implementation, you will need to specify the + --custom-parser or --custom-serializer + option, respectively. The argument format for these two options + is name[=[base][/include]]]. The name + component is the XML Schema type name being customized. Optional + base is a C++ name that should be given to the + generated version. It is normally used as a base for the custom + implementation. Optional include is the header file + that defines the custom implementation. It is #include'ed + into the generated code immediately after (if base + is specified) or instead of the generated version. The following + examples show how we can use these options:

+ +
+--custom-parser foo
+--custom-parser foo=foo_base_pimpl
+--custom-parser foo=foo_base_pimpl/foo/foo-custom.hxx
+--custom-parser foo=/foo/foo-custom.hxx
+  
+ +

The first version instructs the XSD/e compiler not to generate + the parser implementation for the foo XML Schema + type. The second version instructs the compiler to generate + the parser implementation for type foo but call + it foo_base_pimpl. The third version is similar to the + second except that the compiler generates the #include + directive with the foo/foo-custom.hxx file (which + presumably defines foo_pimpl) right after the + foo_base_pimpl class. The last version instructs + the XSD/e compiler to include foo/foo-custom.hxx + instead of generating the parser implementation for + foo. If you omit the last component + (include), then + you can include the custom parser/serializer definitions + using one of the prologue or epilogue XSD/e compiler options. + See the XSD/e + Compiler Command Line Manual for details.

+ +

Once you specify the --custom-parser or + --custom-serializer option, you will need to + provide the custom implementation. You have a choice of either + basing it on the generated version and overriding some + callbacks or implementing it from scratch.

+ +

In the remainder of this section we will examine how to + customize the people parser and serializer + implementations from the example presented in Chapter 4, + "Working with Object Models". Our custom parser + implementation will filter the records being parsed + based on a person's age. Similarly, the serializer will + only serialize records of a specific gender. The code + presented below is taken from the filter + example in the XSD/e distribution. Other examples + related to parser/serializer customization are + wildcard and streaming.

+ +

First, we compile the people.xsd schema + and instruct the XSD/e compiler to customize the + parser and serializer implementations for the people + XML Schema type:

+ +
+$ xsde cxx-hybrid --generate-parser --generate-serializer \
+--custom-parser people=people_base_pimpl/people-custom-pimpl.hxx \
+--custom-serializer people=people_base_simpl/people-custom-simpl.hxx \
+--generate-aggregate people.xsd
+  
+ +

The custom people_pimpl parser implementation + is based on the generated version and is saved to + people-custom-pimpl.hxx:

+ +
+class people_pimpl: public people_base_pimpl
+{
+public:
+  void
+  age_filter (unsigned short min, unsigned short max)
+  {
+    min_age_ = min;
+    max_age_ = max;
+  }
+
+  virtual void
+  person (const ::person& p)
+  {
+    // Check if the age constraints are met.
+    //
+    unsigned short age = p.age ();
+
+    if (age >= min_age_ && age <= max_age_)
+      people_base_pimpl::person (p);
+  }
+
+private:
+  unsigned short min_age_;
+  unsigned short max_age_;
+};
+  
+ +

Here we override the person() callback and, + if the filter conditions are satisfied, call the original + version which adds the person record to the object model. + Note that if the person object model class + were variable-length, then the instance would be + dynamically allocated and passed as a pointer. In this + situation, if we don't use the object, we need to delete it, + for example:

+ +
+virtual void
+person (const ::person* p)
+{
+  unsigned short age = p->age ();
+
+  if (age >= min_age_ && age <= max_age_)
+    people_base_pimpl::person (p);
+  else
+    delete p;
+}
+  
+ +

The custom people_simpl parser implementation + is also based on the generated version and is saved to + people-custom-simpl.hxx:

+ +
+class people_simpl: public people_base_simpl
+{
+public:
+  void
+  gender_filter (gender g)
+  {
+    gender_ = g;
+  }
+
+  virtual bool
+  person_next ()
+  {
+    // See if we have any more person records with the gender we
+    // are interested in.
+    //
+    people::person_const_iterator& i = people_base_simpl_state_.person_;
+    people::person_const_iterator& e = people_base_simpl_state_.person_end_;
+
+    for (; i != e; ++i)
+    {
+      if (i->gender () == gender_)
+        break;
+    }
+
+    return i != e;
+  }
+
+private:
+  gender gender_;
+};
+  
+ +

Here we override the person_next() callback + where we locate the next record that satisfies the filter + conditions. Note that we use the serialization state + provided by the generated people_base_simpl + implementation.

+ +

The following code fragment shows a test driver that uses + the above implementations to filter the data during parsing + and serialization:

+ +
+#include <memory>
+#include <iostream>
+
+#include "people.hxx"
+
+#include "people-pimpl.hxx"
+#include "people-simpl.hxx"
+
+using namespace std;
+
+int
+main (int argc, char* argv[])
+{
+  // Parse.
+  //
+  people_paggr people_p;
+  people_pimpl& root_p = people_p.root_parser ();
+
+  // Initialize the filter.
+  //
+  root_p.age_filter (1, 30);
+
+  xml_schema::document_pimpl doc_p (root_p, people_p.root_name ());
+
+  people_p.pre ();
+  doc_p.parse (argv[1]);
+  auto_ptr<people> ppl (people_p.post ());
+
+  // Print what we've got.
+  //
+  people::person_sequence& ps = ppl->person ();
+
+  for (people::person_iterator i = ps.begin (); i != ps.end (); ++i)
+  {
+    cerr << "first:  " << i->first_name () << endl
+         << "last:   " << i->last_name () << endl
+         << "gender: " << i->gender ().string () << endl
+         << "age:    " << i->age () << endl
+         << endl;
+  }
+
+  // Serialize.
+  //
+  people_saggr people_s;
+  people_simpl& root_s = people_s.root_serializer ();
+
+  // Initialize the filter.
+  //
+  root_s.gender_filter (gender::female);
+
+  xml_schema::document_simpl doc_s (root_s, people_s.root_name ());
+
+  people_s.pre (*ppl);
+  doc_s.serialize (cout, xml_schema::document_simpl::pretty_print);
+  people_s.post ();
+}
+  
+ +

If we run this test driver on the following XML document:

+ +
+<?xml version="1.0"?>
+<people>
+
+  <person>
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+
+  <person>
+    <first-name>Jane</first-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+
+  <person>
+    <first-name>Joe</first-name>
+    <last-name>Dirt</last-name>
+    <gender>male</gender>
+    <age>25</age>
+  </person>
+
+</people>
+  
+ +

We will get the following output:

+ +
+first:  Jane
+last:   Doe
+gender: female
+age:    28
+
+first:  Joe
+last:   Dirt
+gender: male
+age:    25
+
+<people>
+  <person>
+    <first-name>Jane</first-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+</people>
+  
+ + + + +

7 Binary Representation

+ +

Besides reading from and writing to XML, the C++/Hybrid mapping + also allows you to save the object model to and load it from a + number of predefined as well as custom data representation + formats. The predefined binary formats are CDR (Common Data + Representation) and XDR (eXternal Data Representation). A + custom format can easily be supported by providing + insertion and extraction operators for basic types.

+ +

Binary representations contain only the data without any meta + information or markup. Consequently, saving to and loading + from a binary representation can be an order of magnitude + faster as well as result in a much smaller footprint compared + to parsing and serializing the same data in XML. Furthermore, + the resulting representation is normally several times smaller + than the equivalent XML representation. These properties make a + binary representation ideal for internal data exchange and storage. + A typical application that uses this facility stores the data and + communicates within the system using a binary format and reads/writes + the data in XML when communicating with the outside world.

+ +

In order to request the generation of insertion and extraction + operators for a specific predefined or custom data representation + stream, you will need to use the --generate-insertion + and --generate-extraction compiler options. See the + XSD/e + Compiler Command Line Manual for more information.

+ +

The XSD/e runtime provides implementations of the base insertion + and extraction operators for the ACE (Adaptive Communication + Environment) CDR streams and the XDR API. The XDR API is available + out of the box on most POSIX systems as part of Sun RPC. On other + platforms you may need to install a third-party library which + provides the XDR API. + + The XSD/e compiler recognizes two special argument values to the + --generate-insertion and --generate-extraction + options: CDR and XDR. When one of these + arguments is specified, the corresponding implementation from the + XSD/e runtime is automatically used. The following two sections + describe each of these two formats in more detail. It is also + possible to add support for saving the object model to and loading + it from custom data representation formats as discussed in the + last section of this chapter.

+ +

The saving of the object model types to a representation stream + is implemented with stream insertion operators + (operator<<). Similarly, loading of the object + model from a representation stream is implemented with stream + extraction operators (operator>>). The insertion + and extraction operators for the built-in XML Schema types as + well as the sequence templates are provided by the stream + implementation (that is, by the XSD/e runtime in case of CDR and + XDR and by you for custom formats). The XSD/e compiler automatically + generates insertion and extraction operators for the generated object + model types.

+ +

When C++ exceptions are enabled (Section 3.3, "C++ + Exceptions"), the signatures of the insertion and extraction + operators are as follows:

+ +
+void
+operator<< (ostream&, const type&);
+
+void
+operator>> (istream&, type&);
+  
+ +

The insertion and extraction errors are indicated by throwing + stream-specific exceptions. When C++ exceptions are disabled, + the signatures of the insertion and extraction operators are + as follows:

+ +
+bool
+operator<< (ostream&, const type&);
+
+bool
+operator>> (istream&, type&);
+  
+ +

In this case the insertion and extraction operators return + true if the operation was successful and + false otherwise. The stream object may + provide additional error information.

+ + +

7.1 CDR (Common Data Representation)

+ +

When you request the generation of CDR stream insertion and extraction + operators, the ocdrstream and icdrstream + types are defined in the xml_schema namespace. Additionally, + if C++ exceptions are enabled, the cdr_exception exception + is also defined in xml_schema. The icdrstream + and ocdrstream types are simple wrappers for the + ACE_InputCDR and ACE_OutputCDR streams. The following code fragment + shows how we can use these types when C++ exceptions are enabled:

+ +
+try
+{
+  const type& x = ... // Object model.
+
+  // Save to a CDR stream.
+  //
+  ACE_OutputCDR ace_ocdr;
+  xml_schema::ocdrstream ocdr (ace_ocdr);
+
+  ocdr << x;
+
+  // Load from a CDR stream.
+  //
+  ACE_InputCDR ace_icdr (buf, size);
+  xml_schema::icdrstream icdr (ace_icdr);
+
+  type copy;
+  icdr >> copy;
+}
+catch (const xml_schema::cdr_exception&)
+{
+  cerr << "CDR operation failed" << endl;
+}
+  
+ +

The same code fragment but when C++ exceptions are disabled:

+ +
+const type& x = ... // Object model.
+
+// Save to a CDR stream.
+//
+ACE_OutputCDR ace_ocdr;
+xml_schema::ocdrstream ocdr (ace_ocdr);
+
+if (!(ocdr << x))
+{
+  cerr << "CDR operation failed" << endl;
+}
+
+// Load from a CDR stream.
+//
+ACE_InputCDR ace_icdr (buf, size);
+xml_schema::icdrstream icdr (ace_icdr);
+
+type copy;
+
+if (!(icdr >> copy))
+{
+  cerr << "CDR operation failed" << endl;
+}
+  
+ +

The cdr example which can be found in the + examples/cxx/hybrid/binary/ directory of the XSD/e + distribution includes complete source code that shows how to + save the object model to and load it from the CDR format.

+ +

7.2 XDR (eXternal Data Representation)

+ +

When you request the generation of XDR stream insertion and extraction + operators, the oxdrstream and xcdrstream + types are defined in the xml_schema namespace. Additionally, + if C++ exceptions are enabled, the xdr_exception exception + is also defined in xml_schema. The ixdrstream + and oxdrstream types are simple wrappers for the XDR + API. The following code fragment shows how we can use these types + when C++ exceptions are enabled:

+ +
+try
+{
+  const type& x = ... // Object model.
+
+  // Save to a XDR stream.
+  //
+  XDR xdr;
+  xdrrec_create (&xdr, ...);
+  xml_schema::oxdrstream oxdr (xdr);
+
+  oxdr << x;
+
+  // Load from a XDR stream.
+  //
+  xdrrec_create (&xdr, ...);
+  xml_schema::ixdrstream ixdr (xdr);
+
+  type copy;
+  ixdr >> copy;
+}
+catch (const xml_schema::xdr_exception&)
+{
+  cerr << "XDR operation failed" << endl;
+}
+  
+ +

The same code fragment but when C++ exceptions are disabled:

+ +
+const type& x = ... // Object model.
+
+// Save to a XDR stream.
+//
+XDR xdr;
+xdrrec_create (&xdr, ...);
+xml_schema::oxdrstream oxdr (xdr);
+
+if (!(oxdr << x))
+{
+  cerr << "XDR operation failed" << endl;
+}
+
+// Load from a XDR stream.
+//
+xdrrec_create (&xdr, ...);
+xml_schema::ixdrstream ixdr (xdr);
+
+type copy;
+
+if (!(ixdr >> copy))
+{
+  cerr << "XDR operation failed" << endl;
+}
+  
+ +

The xdr example which can be found in the + examples/cxx/hybrid/binary/ directory of the XSD/e + distribution includes complete source code that shows how to + save the object model to and load it from the XDR format.

+ + +

7.3 Custom Representations

+ +

To add support for saving the object model to and loading it + from a custom format, you will need to perform the following + general steps:

+ +
    +
  1. Generate a header file corresponding to the XML Schema + namespace using the --generate-xml-schema + compiler option.
  2. + +
  3. Implement custom stream insertion and extraction operators + for the built-in XML Schema types and sequence templates. + Include the header file obtained in the previous step to + get definitions for these types.
  4. + +
  5. Compile your schemas with the --generate-insertion + and --generate-extraction options. The arguments + to these options will be your custom output and input stream + types, respectively. Use the --hxx-prologue + option to include the definitions for these stream types + into the generated code. Also use the + --extern-xml-schema option to include the + header file obtained in the first step instead of generating + the same code directly.
  6. +
+ +

The custom example which can be found in the + examples/cxx/hybrid/binary/ directory of the XSD/e + distribution includes complete source code that shows how to + save the object model to and load it from a custom format using + the raw binary representation as an example. You can use the + source code from this example as a base to implement support + for your own format.

+ +
+
+ + + + diff --git a/doc/cxx/hybrid/guide/makefile b/doc/cxx/hybrid/guide/makefile new file mode 100644 index 0000000..296a745 --- /dev/null +++ b/doc/cxx/hybrid/guide/makefile @@ -0,0 +1,48 @@ +# file : doc/cxx/hybrid/guide/makefile +# author : Boris Kolpackov +# copyright : Copyright (c) 2006-2011 Code Synthesis Tools CC +# license : GNU GPL v2 + exceptions; see accompanying LICENSE file + +include $(dir $(lastword $(MAKEFILE_LIST)))../../../../build/bootstrap.make + +default := $(out_base)/ +dist := $(out_base)/.dist +dist-win := $(out_base)/.dist-win +cleandoc := $(out_base)/.cleandoc + +# Build. +# +$(default): $(out_base)/cxx-hybrid-e-guide.ps \ + $(out_base)/cxx-hybrid-e-guide.pdf + + +$(out_base)/cxx-hybrid-e-guide.ps: $(src_base)/index.xhtml \ + $(src_base)/figure-1.png \ + $(src_base)/guide.html2ps \ + | $(out_base)/. + $(call message,html2ps $<,html2ps -f $(src_base)/guide.html2ps -o $@ $<) + +$(out_base)/cxx-hybrid-e-guide.pdf: $(out_base)/cxx-hybrid-e-guide.ps | $(out_base)/. + $(call message,ps2pdf $<,ps2pdf14 $< $@) + +# Dist. +# +$(dist): path := $(subst $(src_root)/,,$(src_base)) +$(dist): $(out_base)/cxx-hybrid-e-guide.ps $(out_base)/cxx-hybrid-e-guide.pdf + $(call install-data,$(src_base)/figure-1.png,$(dist_prefix)/$(path)/figure-1.png) + $(call install-data,$(src_base)/index.xhtml,$(dist_prefix)/$(path)/index.xhtml) + $(call install-data,$(out_base)/cxx-hybrid-e-guide.ps,$(dist_prefix)/$(path)/cxx-hybrid-e-guide.ps) + $(call install-data,$(out_base)/cxx-hybrid-e-guide.pdf,$(dist_prefix)/$(path)/cxx-hybrid-e-guide.pdf) + +$(dist-win): $(dist) + + +# Clean. +# +$(cleandoc): + $(call message,rm $$1,rm -f $$1,$(out_base)/cxx-hybrid-e-guide.ps) + $(call message,rm $$1,rm -f $$1,$(out_base)/cxx-hybrid-e-guide.pdf) + +# How to. +# +$(call include,$(bld_root)/install.make) diff --git a/doc/cxx/makefile b/doc/cxx/makefile new file mode 100644 index 0000000..4704c60 --- /dev/null +++ b/doc/cxx/makefile @@ -0,0 +1,20 @@ +# file : doc/cxx/makefile +# author : Boris Kolpackov +# copyright : Copyright (c) 2006-2011 Code Synthesis Tools CC +# license : GNU GPL v2 + exceptions; see accompanying LICENSE file + +include $(dir $(lastword $(MAKEFILE_LIST)))../../build/bootstrap.make + +mappings := hybrid/guide parser/guide serializer/guide + +default := $(out_base)/ +dist := $(out_base)/.dist +dist-win := $(out_base)/.dist-win +cleandoc := $(out_base)/.cleandoc + +$(default): $(addprefix $(out_base)/,$(addsuffix /,$(mappings))) +$(dist): $(addprefix $(out_base)/,$(addsuffix /.dist,$(mappings))) +$(dist-win): $(addprefix $(out_base)/,$(addsuffix /.dist-win,$(mappings))) +$(cleandoc): $(addprefix $(out_base)/,$(addsuffix /.cleandoc,$(mappings))) + +$(foreach m,$(mappings),$(call import,$(src_base)/$m/makefile)) diff --git a/doc/cxx/parser/guide/figure-1.png b/doc/cxx/parser/guide/figure-1.png new file mode 100644 index 0000000..15d1723 Binary files /dev/null and b/doc/cxx/parser/guide/figure-1.png differ diff --git a/doc/cxx/parser/guide/figure-1.svg b/doc/cxx/parser/guide/figure-1.svg new file mode 100644 index 0000000..d994a79 --- /dev/null +++ b/doc/cxx/parser/guide/figure-1.svg @@ -0,0 +1,373 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + class people_pimpl{ void person ();}; + + + + class person_pimpl{ void first_name (string); void last_name (string); void gender (); void age (short); void post_person ();}; + + + + class string_pimpl{ string post_string ();}; + + + class short_pimpl{ short post_short ();}; + + + class gender_pimpl{ void post_gender ();}; + + + + + + + diff --git a/doc/cxx/parser/guide/guide.html2ps b/doc/cxx/parser/guide/guide.html2ps new file mode 100644 index 0000000..bfeca9e --- /dev/null +++ b/doc/cxx/parser/guide/guide.html2ps @@ -0,0 +1,65 @@ +@html2ps { + option { + toc: hb; + colour: 1; + hyphenate: 1; + titlepage: 1; + } + + datefmt: "%B %Y"; + + titlepage { + content: " +
+

Embedded C++/Parser Mapping

+

Getting Started Guide

+

 

+

 

+

 

+

 

+

 

+

 

+
+

Copyright © 2005-2011 CODE SYNTHESIS TOOLS CC

+ +

Permission is granted to copy, distribute and/or modify this + document under the terms of the + GNU Free + Documentation License, version 1.2; with no Invariant Sections, + no Front-Cover Texts and no Back-Cover Texts. +

+ +

This document is available in the following formats: + XHTML, + PDF, and + PostScript.

"; + } + + toc { + indent: 2em; + } + + header { + odd-right: $H; + even-left: $H; + } + + footer { + odd-left: $D; + odd-center: $T; + odd-right: $N; + + even-left: $N; + even-center: $T; + even-right: $D; + } +} + +body { + font-size: 12pt; + text-align: justify; +} + +pre { + font-size: 10pt; +} diff --git a/doc/cxx/parser/guide/index.xhtml b/doc/cxx/parser/guide/index.xhtml new file mode 100644 index 0000000..d070c5a --- /dev/null +++ b/doc/cxx/parser/guide/index.xhtml @@ -0,0 +1,5383 @@ + + + + + + Embedded C++/Parser Mapping Getting Started Guide + + + + + + + + + + + + + +
+
+ +
+ +
+
Embedded C++/Parser Mapping
+
Getting Started Guide
+ +

Copyright © 2005-2011 CODE SYNTHESIS TOOLS CC

+ +

Permission is granted to copy, distribute and/or modify this + document under the terms of the + GNU Free + Documentation License, version 1.2; with no Invariant Sections, + no Front-Cover Texts and no Back-Cover Texts. +

+ +

This document is available in the following formats: + XHTML, + PDF, and + PostScript.

+ +
+ +

Table of Contents

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Preface + + + +
About This Document
More Information
+
1Introduction + + + +
1.1Mapping Overview
1.2Benefits
+
2Hello World Example + + + + + +
2.1Writing XML Document and Schema
2.2Translating Schema to C++
2.3Implementing Application Logic
2.4Compiling and Running
+
3Parser Skeletons + + + + + +
3.1Implementing the Gender Parser
3.2Implementing the Person Parser
3.3Implementing the People Parser
3.4Connecting the Parsers Together
+
4Type Maps + + + + +
4.1Object Model
4.2Type Map File Format
4.3Parser Implementations
+
5Mapping Configuration + + + + + + + + + + +
5.1Standard Template Library
5.2Input/Output Stream Library
5.3C++ Exceptions
5.4XML Schema Validation
5.564-bit Integer Type
5.6Parser Reuse
5.7Support for Polymorphism
5.8Custom Allocators
5.9A Minimal Example
+
6Built-In XML Schema Type Parsers + + + + + + + + + + + + + + +
6.1QName Parser
6.2NMTOKENS and IDREFS Parsers
6.3base64Binary and hexBinary Parsers
6.4Time Zone Representation
6.5date Parser
6.6dateTime Parser
6.7duration Parser
6.8gDay Parser
6.9gMonth Parser
6.10gMonthDay Parser
6.11gYear Parser
6.12gYearMonth Parser
6.13time Parser
+
7Document Parser and Error Handling + + + + + +
7.1Document Parser
7.2Exceptions
7.3Error Codes
7.4Reusing Parsers after an Error
+
Appendix A — Supported XML Schema Constructs
+
+ +

Preface

+ +

About This Document

+ +

The goal of this document is to provide you with an + understanding of the C++/Parser programming model and allow you + to efficiently evaluate XSD/e against your project's technical + requirements. As such, this document is intended for embedded + C++ developers and software architects who are looking for an + embedded XML processing solution. Prior experience with XML + and C++ is required to understand this document. Basic + understanding of XML Schema is advantageous but not expected + or required. +

+ + +

More Information

+ +

Beyond this guide, you may also find the following sources of + information useful:

+ +
    +
  • XSD/e + Compiler Command Line Manual
  • + +
  • The INSTALL file in the XSD/e distribution provides + build instructions for various platforms.
  • + +
  • The examples/cxx/parser/ directory in the XSD/e + distribution contains a collection of examples and a README + file with an overview of each example.
  • + +
  • The xsde-users + mailing list is the place to ask technical questions about XSD/e and the + Embedded C++/Parser mapping. Furthermore, the + archives + may already have answers to some of your questions.
  • + +
+ + + +

1 Introduction

+ +

Welcome to CodeSynthesis XSD/e and the Embedded C++/Parser mapping. + XSD/e is a dependency-free W3C XML Schema to C++ compiler for mobile, + embedded, and light-weight applications. Embedded C++/Parser is an + XML Schema to C++ mapping that represents an XML vocabulary as a set + of parser skeletons which you can implement to perform XML processing + as required by your application logic. +

+ +

1.1 Mapping Overview

+ +

The Embedded C++/Parser mapping provides event-driven, stream-oriented + XML parsing, XML Schema validation, and C++ data binding. It was + specifically designed and optimized for mobile and embedded + systems where hardware constraints require high efficiency and + economical use of resources. As a result, the generated + parsers are 2-10 times faster than general-purpose validating + XML parsers while at the same time maintaining extremely low static + and dynamic memory footprints. For example, a validating parser + executable can be as small as 120KB in size. The size can be + further reduced by disabling support for XML Schema validation. +

+ +

The generated code and the runtime library are also highly-portable + and, in their minimal configuration, can be used without STL, RTTI, + iostream, C++ exceptions, and C++ templates.

+ +

To speed up application development, the C++/Parser mapping + can be instructed to generate sample parser implementations + and a test driver which can then be filled with the application + logic code. The mapping also provides a wide range of + mechanisms for controlling and customizing the generated code.

+ +

The next chapter shows how to create a simple application + that uses the Embedded C++/Parser mapping to parse, validate, + and extract data from a simple XML instance document. The + following chapters describe the Embedded C++/Parser mapping + in more detail.

+ +

1.2 Benefits

+ +

Traditional XML access APIs such as Document Object Model (DOM) + or Simple API for XML (SAX) as well as general-purpose XML Schema + validators have a number of drawbacks that make them less suitable + for creating mobile and embedded XML processing applications. These + drawbacks include: +

+ +
    +
  • Text-based representation results in inefficient use of + resources.
  • + +
  • Extra validation code that is not used by the application.
  • + +
  • Generic representation of XML in terms of elements, attributes, + and text forces an application developer to write a substantial + amount of bridging code that identifies and transforms pieces + of information encoded in XML to a representation more suitable + for consumption by the application logic.
  • + +
  • String-based flow control defers error detection to runtime. + It also reduces code readability and maintainability.
  • + +
  • Lack of type safety because all information is represented + as text.
  • + +
  • Resulting applications are hard to debug, change, and + maintain.
  • +
+ +

In contrast, statically-typed, vocabulary-specific parser + skeletons produced by the Embedded C++/Parser mapping use + native data representations (for example, integers are passed as + integers, not as text) and include validation code only for + XML Schema constructs that are used in the application. This + results in efficient use of resources and compact object code.

+ +

Furthermore, the parser skeletons allow you to operate in your + domain terms instead of the generic elements, attributes, and + text. Static typing helps catch errors at compile-time rather + than at run-time. Automatic code generation frees you for more + interesting tasks (such as doing something useful with the + information stored in the XML documents) and minimizes the + effort needed to adapt your applications to changes in the + document structure. To summarize, the C++/Parser mapping has + the following key advantages over generic XML access APIs:

+ +
    +
  • Ease of use. The generated code hides all the complexity + associated with recreating the document structure, maintaining the + dispatch state, and converting the data from the text representation + to data types suitable for manipulation by the application logic. + Parser skeletons also provide a convenient mechanism for building + custom in-memory representations.
  • + +
  • Natural representation. The generated parser skeletons + implement parser callbacks as virtual functions with names + corresponding to elements and attributes in XML. As a result, + you process the XML data using your domain vocabulary instead + of generic elements, attributes, and text. +
  • + +
  • Concise code. With a separate parser skeleton for each + XML Schema type, the application implementation is + simpler and thus easier to read and understand.
  • + +
  • Safety. The XML data is delivered to parser callbacks as + statically typed objects. The parser callbacks themselves are virtual + functions. This helps catch programming errors at compile-time + rather than at runtime.
  • + +
  • Maintainability. Automatic code generation minimizes the + effort needed to adapt the application to changes in the + document structure. With static typing, the C++ compiler + can pin-point the places in the application code that need to be + changed.
  • + +
  • Efficiency. The generated parser skeletons use native + data representations and combine data extraction, validation, + and even dispatching in a single step. This makes them much + more efficient than traditional architectures with separate + stages for validation and data extraction/dispatch.
  • +
+ + + + + +

2 Hello World Example

+ +

In this chapter we will examine how to parse a very simple XML + document using the XSD/e-generated C++/Parser skeletons. + + All the code presented in this chapter is based on the hello + example which can be found in the examples/cxx/parser/ + directory of the XSD/e distribution.

+ +

2.1 Writing XML Document and Schema

+ +

First, we need to get an idea about the structure + of the XML documents we are going to process. Our + hello.xml, for example, could look like this:

+ +
+<?xml version="1.0"?>
+<hello>
+
+  <greeting>Hello</greeting>
+
+  <name>sun</name>
+  <name>moon</name>
+  <name>world</name>
+
+</hello>
+      
+ +

Then we can write a description of the above XML in the + XML Schema language and save it into hello.xsd:

+ +
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="hello">
+    <xs:sequence>
+      <xs:element name="greeting" type="xs:string"/>
+      <xs:element name="name" type="xs:string" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="hello" type="hello"/>
+
+</xs:schema>
+      
+ +

Even if you are not familiar with the XML Schema language, it + should be easy to connect declarations in hello.xsd + to elements in hello.xml. The hello type + is defined as a sequence of the nested greeting and + name elements. Note that the term sequence in XML + Schema means that elements should appear in a particular order + as opposed to appearing multiple times. The name + element has its maxOccurs property set to + unbounde which means it can appear multiple times + in an XML document. Finally, the globally-defined hello + element prescribes the root element for our vocabulary. For an + easily-approachable introduction to XML Schema refer to + XML Schema Part 0: + Primer.

+ +

The above schema is a specification of our vocabulary; it tells + everybody what valid XML instances of our vocabulary should look + like. The next step is to compile this schema to generate C++ parser + skeletons.

+ +

2.2 Translating Schema to C++

+ +

Now we are ready to translate our hello.xsd to C++ parser + skeletons. To do this we invoke the XSD/e compiler from a terminal + (UNIX) or a command prompt (Windows): +

+ +
+$ xsde cxx-parser hello.xsd
+  
+ +

The XSD/e compiler produces two C++ files: hello-pskel.hxx + and hello-pskel.cxx. The following code fragment is taken + from hello-pskel.hxx; it should give you an idea about what + gets generated: +

+ +
+class hello_pskel
+{
+public:
+  // Parser callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual void
+  greeting (const std::string&);
+
+  virtual void
+  name (const std::string&);
+
+  virtual void
+  post_hello ();
+
+  // Parser construction API.
+  //
+  void
+  greeting_parser (xml_schema::string_pskel&);
+
+  void
+  name_parser (xml_schema::string_pskel&);
+
+  void
+  parsers (xml_schema::string_pskel& /* greeting */,
+           xml_schema::string_pskel& /* name */);
+
+private:
+  ...
+};
+  
+ +

The first four member functions shown above are called parser + callbacks. You would normally override them in your implementation + of the parser to do something useful. Let's go through all of + them one by one.

+ +

The pre() function is an initialization callback. It is + called when a new element of type hello is about + to be parsed. You would normally use this function to allocate a new + instance of the resulting type or clear accumulators that are used + to gather information during parsing. The default implementation + of this function does nothing.

+ +

The post_hello() function is a finalization callback. Its + name is constructed by adding the parser skeleton name to the + post_ prefix. The finalization callback is called when + parsing of the element is complete and the result, if any, should + be returned. Note that in our case the return type of + post_hello() is void which means there + is nothing to return. More on parser return types later. +

+ +

You may be wondering why the finalization callback is called + post_hello() instead of post() just + like pre(). The reason for this is that + finalization callbacks can have different return types and + result in function signature clashes across inheritance + hierarchies. To prevent this, the signatures of finalization + callbacks are made unique by adding the type name to their names.

+ +

The greeting() and name() functions are + called when the greeting and name elements + have been parsed, respectively. Their arguments are of type + std::string and contain the data extracted from XML.

+ +

The last three functions are for connecting parsers to each other. + For example, there is a predefined parser for built-in XML Schema type + string in the XSD/e runtime. We will be using + it to parse the contents of greeting and + name elements, as shown in the next section.

+ +

2.3 Implementing Application Logic

+ +

At this point we have all the parts we need to do something useful + with the information stored in XML documents. The first step is + to implement the parser: +

+ +
+#include <iostream>
+#include "hello-pskel.hxx"
+
+class hello_pimpl: public hello_pskel
+{
+public:
+  virtual void
+  greeting (const std::string& g)
+  {
+    greeting_ = g;
+  }
+
+  virtual void
+  name (const std::string& n)
+  {
+    std::cout << greeting_ << ", " << n << "!" << std::endl;
+  }
+
+private:
+  std::string greeting_;
+};
+  
+ +

We left both pre() and post_hello() with the + default implementations; we don't have anything to initialize or + return. The rest is pretty straightforward: we store the greeting + in a member variable and later, when parsing names, use it to + say hello.

+ +

An observant reader my ask what happens if the name + element comes before greeting? Don't we need to + make sure greeting_ was initialized and report + an error otherwise? The answer is no, we don't have to do + any of this. The hello_pskel parser skeleton + performs validation of XML according to the schema from which + it was generated. As a result, it will check the order + of the greeting and name elements + and report an error if it is violated.

+ +

Now it is time to put this parser implementation to work:

+ +
+using namespace std;
+
+int
+main (int argc, char* argv[])
+{
+  try
+  {
+    // Construct the parser.
+    //
+    xml_schema::string_pimpl string_p;
+    hello_pimpl hello_p;
+
+    hello_p.greeting_parser (string_p);
+    hello_p.name_parser (string_p);
+
+    // Parse the XML instance.
+    //
+    xml_schema::document_pimpl doc_p (hello_p, "hello");
+
+    hello_p.pre ();
+    doc_p.parse (argv[1]);
+    hello_p.post_hello ();
+  }
+  catch (const xml_schema::parser_exception& e)
+  {
+    cerr << argv[1] << ":" << e.line () << ":" << e.column ()
+         << ": " << e.text () << endl;
+    return 1;
+  }
+}
+  
+ +

The first part of this code snippet instantiates individual parsers + and assembles them into a complete vocabulary parser. + xml_schema::string_pimpl is an implementation of a parser + for built-in XML Schema type string. It is provided by + the XSD/e runtime along with parsers for other built-in types (for + more information on the built-in parsers see Chapter 6, + "Built-In XML Schema Type Parsers"). We use string_pimpl + to parse the greeting and name elements as + indicated by the calls to greeting_parser() and + name_parser(). +

+ +

Then we instantiate a document parser (doc_p). The + first argument to its constructor is the parser for + the root element (hello_p in our case). The + second argument is the root element name. +

+ +

The final piece is the calls to pre(), parse(), + and post_hello(). The call to parse() + perform the actual XML parsing while the calls to pre() and + post_hello() make sure that the parser for the root + element can perform proper initialization and cleanup.

+ +

While our parser implementation and test driver are pretty small and + easy to write by hand, for bigger XML vocabularies it can be a + substantial effort. To help with this task XSD/e can automatically + generate sample parser implementations and a test driver from your + schemas. You can request the generation of a sample implementation with + empty function bodies by specifying the --generate-noop-impl + option. Or you can generate a sample implementation that prints the + data store in XML by using the --generate-print-impl + option. To request the generation of a test driver you can use the + --generate-test-driver option. For more information + on these options refer to the + XSD/e + Compiler Command Line Manual. The 'generated' example + in the XSD/e distribution shows the sample implementation generation + feature in action.

+ + +

2.4 Compiling and Running

+ +

After saving all the parts from the previous section in + driver.cxx, we are ready to compile our first + application and run it on the test XML document. On UNIX + this can be done with the following commands: +

+ +
+$ c++ -I.../libxsde -c driver.cxx hello-pskel.cxx
+$ c++ -o driver driver.o hello-pskel.o .../libxsde/xsde/libxsde.a
+$ ./driver hello.xml
+Hello, sun!
+Hello, moon!
+Hello, world!
+  
+ +

Here .../libxsde represents the path to the + libxsde directory in the XSD/e distribution. + We can also test the error handling. To test XML well-formedness + checking, we can try to parse hello-pskel.hxx:

+ +
+$ ./driver hello-pskel.hxx
+hello-pskel.hxx:1:0: not well-formed (invalid token)
+  
+ +

We can also try to parse a valid XML but not from our + vocabulary, for example hello.xsd:

+ +
+$ ./driver hello.xsd
+hello.xsd:2:57: unexpected element encountered
+  
+ + + + + +

3 Parser Skeletons

+ +

As we have seen in the previous chapter, the XSD/e compiler generates + a parser skeleton class for each type defined in XML Schema. In + this chapter we will take a closer look at different functions + that comprise a parser skeleton as well as the way to connect + our implementations of these parser skeletons to create a complete + parser.

+ +

In this and subsequent chapters we will use the following schema + that describes a collection of person records. We save it in + people.xsd:

+ +
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:simpleType name="gender">
+    <xs:restriction base="xs:string">
+      <xs:enumeration value="male"/>
+      <xs:enumeration value="female"/>
+    </xs:restriction>
+  </xs:simpleType>
+
+  <xs:complexType name="person">
+    <xs:sequence>
+      <xs:element name="first-name" type="xs:string"/>
+      <xs:element name="last-name" type="xs:string"/>
+      <xs:element name="gender" type="gender"/>
+      <xs:element name="age" type="xs:short"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:complexType name="people">
+    <xs:sequence>
+      <xs:element name="person" type="person" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="people" type="people"/>
+
+</xs:schema>
+  
+ +

A sample XML instance to go along with this schema is saved + in people.xml:

+ +
+<?xml version="1.0"?>
+<people>
+  <person>
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+  <person>
+    <first-name>Jane</first-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+</people>
+  
+ +

Compiling people.xsd with the XSD/e compiler results + in three parser skeletons being generated: gender_pskel, + person_pskel, and people_pskel. We are going + to examine and implement each of them in the subsequent sections.

+ +

3.1 Implementing the Gender Parser

+ +

The generated gender_pskel parser skeleton looks like + this:

+ +
+class gender_pskel: public xml_schema::string_pskel
+{
+public:
+  gender_pskel (xml_schema::string_pskel* base_impl);
+
+  // Parser callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual void
+  post_gender ();
+};
+  
+ +

Notice that gender_pskel inherits from + xml_schema::string_pskel which is a parser skeleton + for built-in XML Schema type string and is + predefined in the XSD/e runtime library. This is an example + of the general rule that parser skeletons follow: if a type + in XML Schema inherits from another then there will be an + equivalent inheritance between the corresponding parser + skeleton classes. The gender_pskel class also + declares a constructor which expects a pointer to the base + parser skeleton. We will discuss the purpose of this + constructor shortly.

+ +

The pre() and post_gender() callbacks + should look familiar from the previous chapter. Let's now + implement the parser. Our implementation will simply print + the gender to cout:

+ + +
+class gender_pimpl: public gender_pskel
+{
+public:
+  gender_pimpl ()
+    : gender_pskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  post_gender ()
+  {
+    std::string s = post_string ();
+    cout << "gender: " << s << endl;
+  }
+
+private:
+  xml_schema::string_pimpl base_impl_;
+};
+  
+ +

While the code is quite short, there is a lot going on. First, + notice that we define a member variable base_impl_ + of type xml_schema::string_pimpl and then pass + it to the gender_pskel's constructor. We have + encountered xml_schema::string_pimpl already; it is an + implementation of the xml_schema::string_pskel parser + skeleton for built-in XML Schema type string. By + passing base_impl_ to the gender_pskel's + constructor we provide an implementation for the part of the + parser skeleton that is inherited from string_pskel.

+ +

This is another common theme in the C++/Parser programming model: + reusing implementations of the base parsers in the derived ones. + In our case, string_pimpl will do all the dirty work + of extracting the data and we can just get it at the end with the + call to post_string(). For more information on parser + implementation reuse refer to Section 5.6, + "Parser Reuse".

+ +

In case you are curious, here are the definitions for + xml_schema::string_pskel and + xml_schema::string_pimpl:

+ +
+namespace xml_schema
+{
+  class string_pskel: public parser_simple_content
+  {
+  public:
+    virtual std::string
+    post_string () = 0;
+  };
+
+  class string_pimpl: public string_pskel
+  {
+  public:
+    virtual void
+    _pre ();
+
+    virtual void
+    _characters (const xml_schema::ro_string&);
+
+    virtual std::string
+    post_string ();
+
+  protected:
+    std::string str_;
+  };
+}
+  
+ +

There are three new pieces in this code that we haven't seen yet. + Those are the parser_simple_content class and + the _pre() and _characters() functions. + The parser_simple_content class is defined in the XSD/e + runtime and is a base class for all parser skeletons that conform + to the simple content model in XML Schema. Types with the + simple content model cannot have nested elements—only text + and attributes. There is also the parser_complex_content + class which corresponds to the complex content mode (types with + nested elements, for example, person from + people.xsd).

+ +

The _pre() function is a parser callback. Remember we + talked about the pre() and post_*() callbacks + in the previous chapter? There are actually two more callbacks + with similar roles: _pre() and _post (). + As a result, each parser skeleton has four special callbacks:

+ +
+  virtual void
+  pre ();
+
+  virtual void
+  _pre ();
+
+  virtual void
+  _post ();
+
+  virtual void
+  post_name ();
+  
+ +

pre() and _pre() are initialization + callbacks. They get called in that order before a new instance of the type + is about to be parsed. The difference between pre() and + _pre() is conventional: pre() can + be completely overridden by a derived parser. The derived + parser can also override _pre() but has to always call + the original version. This allows you to partition initialization + into customizable and required parts.

+ +

Similarly, _post() and post_name() are + finalization callbacks with exactly the same semantics: + post_name() can be completely overridden by the derived + parser while the original _post() should always be called. +

+ +

The final bit we need to discuss in this section is the + _characters() function. As you might have guessed, it + is also a callback. A low-level one that delivers raw character content + for the type being parsed. You will seldom need to use this callback + directly. Using implementations for the built-in parsers provided by + the XSD/e runtime is usually a simpler and more convenient + alternative.

+ +

At this point you might be wondering why some post_*() + callbacks, for example post_string(), return some data + while others, for example post_gender(), have + void as a return type. This is a valid concern + and it will be addressed in the next chapter.

+ +

3.2 Implementing the Person Parser

+ +

The generated person_pskel parser skeleton looks like + this:

+ +
+class person_pskel: public xml_schema::parser_complex_content
+{
+public:
+  // Parser callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual void
+  first_name (const std::string&);
+
+  virtual void
+  last_name (const std::string&);
+
+  virtual void
+  gender ();
+
+  virtual void
+  age (short);
+
+  virtual void
+  post_person ();
+
+  // Parser construction API.
+  //
+  void
+  first_name_parser (xml_schema::string_pskel&);
+
+  void
+  last_name_parser (xml_schema::string_pskel&);
+
+  void
+  gender_parser (gender_pskel&);
+
+  void
+  age_parser (xml_schema::short_pskel&);
+
+  void
+  parsers (xml_schema::string_pskel& /* first-name */,
+           xml_schema::string_pskel& /* last-name */,
+           gender_pskel&             /* gender */,
+           xml_schema::short_pskel&  /* age */);
+};
+  
+ + +

As you can see, we have a parser callback for each of the nested + elements found in the person XML Schema type. + The implementation of this parser is straightforward:

+ +
+class person_pimpl: public person_pskel
+{
+public:
+  virtual void
+  first_name (const std::string& n)
+  {
+    cout << "first: " << f << endl;
+  }
+
+  virtual void
+  last_name (const std::string& l)
+  {
+    cout << "last: " << l << endl;
+  }
+
+  virtual void
+  age (short a)
+  {
+    cout << "age: " << a << endl;
+  }
+};
+  
+ +

Notice that we didn't override the gender() callback + because all the printing is done by gender_pimpl.

+ +

3.3 Implementing the People Parser

+ +

The generated people_pskel parser skeleton looks like + this:

+ +
+class people_pskel: public xml_schema::parser_complex_content
+{
+public:
+  // Parser callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual void
+  person ();
+
+  virtual void
+  post_people ();
+
+  // Parser construction API.
+  //
+  void
+  person_parser (person_pskel&);
+
+  void
+  parsers (person_pskel& /* person */);
+};
+  
+ +

The person() callback will be called after parsing each + person element. While person_pimpl does + all the printing, one useful thing we can do in this callback is to + print an extra newline after each person record so that our + output is more readable:

+ +
+class people_pimpl: public people_pskel
+{
+public:
+  virtual void
+  person ()
+  {
+    cout << endl;
+  }
+};
+  
+ +

Now it is time to put everything together.

+ + +

3.4 Connecting the Parsers Together

+ +

At this point we have all the individual parsers implemented + and can proceed to assemble them into a complete parser + for our XML vocabulary. The first step is to instantiate + all the individual parsers that we will need:

+ +
+xml_schema::short_pimpl short_p;
+xml_schema::string_pimpl string_p;
+
+gender_pimpl gender_p;
+person_pimpl person_p;
+people_pimpl people_p;
+  
+ +

Notice that our schema uses two built-in XML Schema types: + string for the first-name and + last-name elements as well as short + for age. We will use predefined parsers that + come with the XSD/e runtime to handle these types. The next + step is to connect all the individual parsers. We do this + with the help of functions defined in the parser + skeletons and marked with the "Parser Construction API" + comment. One way to do it is to connect each individual + parser by calling the *_parser() functions:

+ +
+person_p.first_name_parser (string_p);
+person_p.last_name_parser (string_p);
+person_p.gender_parser (gender_p);
+person_p.age_parser (short_p);
+
+people_p.person_parser (person_p);
+  
+ +

You might be wondering what happens if you do not provide + a parser by not calling one of the *_parser() functions. + In that case the corresponding XML content will be skipped, + including validation. This is an efficient way to ignore parts + of the document that you are not interested in.

+ + +

An alternative, shorter, way to connect the parsers is by using + the parsers() functions which connects all the parsers + for a given type at once:

+ +
+person_p.parsers (string_p, string_p, gender_p, short_p);
+people_p.parsers (person_p);
+  
+ +

The following figure illustrates the resulting connections. Notice + the correspondence between return types of the post_*() + functions and argument types of element callbacks that are connected + by the arrows.

+ + +
+ +

The last step is the construction of the document parser and + invocation of the complete parser on our sample XML instance:

+ +
+xml_schema::document_pimpl doc_p (people_p, "people");
+
+people_p.pre ();
+doc_p.parse ("people.xml");
+people_p.post_people ();
+  
+ +

Let's consider xml_schema::document_pimpl in + more detail. While the exact definition of this class + varies depending on the mapping configuration, here is + the part relevant to our example:

+ +
+namespace xml_schema
+{
+  class document_pimpl
+  {
+  public:
+    document_pimpl (xml_schema::parser_base&,
+                    const std::string& root_element_name);
+
+    document_pimpl (xml_schema::parser_base&,
+                    const std::string& root_element_namespace,
+                    const std::string& root_element_name);
+
+    void
+    parse (const std::string& file);
+
+    void
+    parse (std::istream&);
+
+    void
+    parse (const void* data, size_t size, bool last);
+  };
+}
+  
+ +

xml_schema::document_pimpl is a root parser for + the vocabulary. The first argument to its constructors is the + parser for the type of the root element (people_pimpl + in our case). Because a type parser is only concerned with + the element's content and not with the element's name, we need + to specify the root element name somewhere. That's + what is passed as the second and third arguments to the + document_pimpl's constructors.

+ +

There are also three overloaded parse() function + defined in the document_pimpl class. The first version + parses a local file identified by a name. The second version + reads the data from an input stream. The last version allows + you to parse the data directly from a buffer, one chunk at a + time. You can call this function multiple times with the final + call having the last argument set to true. For more + information on the xml_schema::document_pimpl class + refer to Chapter 7, "Document Parser and Error + Handling".

+ +

Let's now consider a step-by-step list of actions that happen + as we parse through people.xml. The content of + people.xml is repeated below for convenience.

+ +
+<?xml version="1.0"?>
+<people>
+  <person>
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+  <person>
+    <first-name>Jane</first-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+</people>
+  
+ + +
    +
  1. people_p.pre() is called from + main(). We did not provide any implementation + for this callback so this call is a no-op.
  2. + +
  3. doc_p.parse("people.xml") is called from + main(). The parser opens the file and starts + parsing its content.
  4. + +
  5. The parser encounters the root element. doc_p + verifies that the root element is correct and calls + _pre() on people_p which is also + a no-op. Parsing is now delegated to people_p.
  6. + +
  7. The parser encounters the person element. + people_p determines that person_p + is responsible for parsing this element. pre() + and _pre() callbacks are called on person_p. + Parsing is now delegated to person_p.
  8. + +
  9. The parser encounters the first-name element. + person_p determines that string_p + is responsible for parsing this element. pre() + and _pre() callbacks are called on string_p. + Parsing is now delegated to string_p.
  10. + +
  11. The parser encounters character content consisting of + "John". The _characters() callback is + called on string_p.
  12. + +
  13. The parser encounters the end of first-name + element. The _post() and post_string() + callbacks are called on string_p. The + first_name() callback is called on person_p + with the return value of post_string(). The + first_name() implementation prints + "first: John" to cout. + Parsing is now returned to person_p.
  14. + +
  15. Steps analogous to 5-7 are performed for the last-name, + gender, and age elements.
  16. + +
  17. The parser encounters the end of person + element. The _post() and post_person() + callbacks are called on person_p. The + person() callback is called on people_p. + The person() implementation prints a new line + to cout. Parsing is now returned to + people_p.
  18. + +
  19. Steps 4-9 are performed for the second person + element.
  20. + +
  21. The parser encounters the end of people + element. The _post() callback is called on + people_p. The doc_p.parse("people.xml") + call returns to main().
  22. + +
  23. people_p.post_people() is called from + main() which is a no-op.
  24. + +
+ + + + + +

4 Type Maps

+ +

There are many useful things you can do inside parser callbacks as they + are right now. There are, however, times when you want to propagate + some information from one parser to another or to the caller of the + parser. One common task that would greatly benefit from such a + possibility is building a tree-like in-memory object model of the + data stored in XML. During execution, each individual sub-parser + would create a sub-tree and return it to its parent parser + which can then incorporate this sub-tree into the whole tree.

+ +

In this chapter we will discuss the mechanisms offered by the + C++/Parser mapping for returning information from individual + parsers and see how to use them to build an object model + of our people vocabulary.

+ +

4.1 Object Model

+ +

An object model for our person record example could + look like this (saved in the people.hxx file):

+ +
+#include <string>
+#include <vector>
+
+enum gender
+{
+  male,
+  female
+};
+
+class person
+{
+public:
+  person (const std::string& first,
+          const std::string& last,
+          ::gender gender,
+          short age)
+    : first_ (first), last_ (last),
+      gender_ (gender), age_ (age)
+  {
+  }
+
+  const std::string&
+  first () const
+  {
+    return first_;
+  }
+
+  const std::string&
+  last () const
+  {
+    return last_;
+  }
+
+  ::gender
+  gender () const
+  {
+    return gender_;
+  }
+
+  short
+  age () const
+  {
+    return age_;
+  }
+
+private:
+  std::string first_;
+  std::string last_;
+  ::gender gender_;
+  short age_;
+};
+
+typedef std::vector<person> people;
+  
+ +

While it is clear which parser is responsible for which part of + the object model, it is not exactly clear how, for + example, gender_pimpl will deliver gender + to person_pimpl. You might have noticed that + string_pimpl manages to deliver its value to the + first_name() callback of person_pimpl. Let's + see how we can utilize the same mechanism to propagate our + own data.

+ +

There is a way to tell the XSD/e compiler that you want to + exchange data between parsers. More precisely, for each + type defined in XML Schema, you can tell the compiler two things. + First, the return type of the post_*() callback + in the parser skeleton generated for this type. And, second, + the argument type for callbacks corresponding to elements and + attributes of this type. For example, for XML Schema type + gender we can specify the return type for + post_gender() in the gender_pskel + skeleton and the argument type for the gender() callback + in the person_pskel skeleton. As you might have guessed, + the generated code will then pass the return value from the + post_*() callback as an argument to the element or + attribute callback.

+ +

The way to tell the XSD/e compiler about these XML Schema to + C++ mappings is with type map files. Here is a simple type + map for the gender type from the previous paragraph.

+ +
+include "people.hxx";
+gender ::gender ::gender;
+  
+ +

The first line indicates that the generated code must include + people.hxx in order to get the definition for the + gender type. The second line specifies that both + argument and return types for the gender + XML Schema type should be the ::gender C++ enum + (we use fully-qualified C++ names to avoid name clashes). + The next section will describe the type map format in detail. + We save this type map in people.map and + then translate our schemas with the --type-map + option to let the XSD/e compiler know about our type map:

+ +
+$ xsde cxx-parser --type-map people.map people.xsd
+  
+ +

If we now look at the generated people-pskel.hxx, + we will see the following changes in the gender_pskel and + person_pskel skeletons:

+ +
+#include "people.hxx"
+
+class gender_pskel: public xml_schema::string_pskel
+{
+  virtual ::gender
+  post_gender () = 0;
+
+  ...
+};
+
+class person_pskel: public xml_schema::parser_complex_content
+{
+  virtual void
+  gender (::gender);
+
+  ...
+};
+  
+ +

Notice that #include "people.hxx" was added to + the generated header file from the type map to provide the + definition for the gender enum.

+ +

4.2 Type Map File Format

+ +

Type map files are used to define a mapping between XML Schema + and C++ types. The compiler uses this information + to determine return types of post_*() + callbacks in parser skeletons corresponding to XML Schema + types as well as argument types for callbacks corresponding + to elements and attributes of these types.

+ +

The compiler has a set of predefined mapping rules that map the + built-in XML Schema types to suitable C++ types (discussed + below) and all other types to void. + By providing your own type maps you can override these predefined + rules. The format of the type map file is presented below: +

+ +
+namespace <schema-namespace> [<cxx-namespace>]
+{
+  (include <file-name>;)*
+  ([type] <schema-type> <cxx-ret-type> [<cxx-arg-type>];)*
+}
+  
+ +

Both <schema-namespace> and + <schema-type> are regex patterns while + <cxx-namespace>, + <cxx-ret-type>, and + <cxx-arg-type> are regex pattern + substitutions. All names can be optionally enclosed in + " ", for example, to include white-spaces.

+ +

<schema-namespace> determines XML + Schema namespace. Optional <cxx-namespace> + is prefixed to every C++ type name in this namespace declaration. + <cxx-ret-type> is a C++ type name that is + used as a return type for the post_*() callback. + Optional <cxx-arg-type> is an argument + type for callbacks corresponding to elements and attributes + of this type. If <cxx-arg-type> is not + specified, it defaults to <cxx-ret-type> + if <cxx-ret-type> ends with * or + & (that is, it is a pointer or a reference) and + const <cxx-ret-type>& + otherwise. + <file-name> is a file name either in the + " " or < > format + and is added with the #include directive to + the generated code.

+ +

The # character starts a comment that ends + with a new line or end of file. To specify a name that contains + # enclose it in " ". + For example:

+ +
+namespace http://www.example.com/xmlns/my my
+{
+  include "my.hxx";
+
+  # Pass apples by value.
+  #
+  apple apple;
+
+  # Pass oranges as pointers.
+  #
+  orange orange_t*;
+}
+  
+ +

In the example above, for the + http://www.example.com/xmlns/my#orange + XML Schema type, the my::orange_t* C++ type will + be used as both return and argument types.

+ +

Several namespace declarations can be specified in a single + file. The namespace declaration can also be completely + omitted to map types in a schema without a namespace. For + instance:

+ +
+include "my.hxx";
+apple apple;
+
+namespace http://www.example.com/xmlns/my
+{
+  orange "const orange_t*";
+}
+  
+ +

The compiler has a number of predefined mapping rules for + the built-in XML Schema types which can be presented as the + following map files:

+ +
+namespace http://www.w3.org/2001/XMLSchema
+{
+  boolean bool bool;
+
+  byte "signed char" "signed char";
+  unsignedByte "unsigned char" "unsigned char";
+
+  short short short;
+  unsignedShort "unsigned short" "unsigned short";
+
+  int int int;
+  unsignedInt "unsigned int" "unsigned int";
+
+  long "long long" "long long";
+  unsignedLong "unsigned long long" "unsigned long long";
+
+  integer long long;
+
+  negativeInteger long long;
+  nonPositiveInteger long long;
+
+  positiveInteger "unsigned long" "unsigned long";
+  nonNegativeInteger "unsigned long" "unsigned long";
+
+  float float float;
+  double double double;
+  decimal double double;
+
+  NMTOKENS xml_schema::string_sequence*;
+  IDREFS xml_schema::string_sequence*;
+
+  base64Binary xml_schema::buffer*;
+  hexBinary xml_schema::buffer*;
+
+  date xml_schema::date;
+  dateTime xml_schema::date_time;
+  duration xml_schema::duration;
+  gDay xml_schema::gday;
+  gMonth xml_schema::gmonth;
+  gMonthDay xml_schema::gmonth_day;
+  gYear xml_schema::gyear;
+  gYearMonth xml_schema::gyear_month;
+  time xml_schema::time;
+}
+  
+ +

If STL is enabled (Section 5.1, "Standard Template + Library"), the following mapping is used for the string-based + XML Schema built-in types:

+ +
+namespace http://www.w3.org/2001/XMLSchema
+{
+  include <string>;
+
+  anySimpleType std::string;
+
+  string std::string;
+  normalizedString std::string;
+  token std::string;
+  Name std::string;
+  NMTOKEN std::string;
+  NCName std::string;
+  ID std::string;
+  IDREF std::string;
+  language std::string;
+  anyURI std::string;
+
+  QName xml_schema::qname;
+}
+  
+ +

Otherwise, a C string-based mapping is used:

+ +
+namespace http://www.w3.org/2001/XMLSchema
+{
+  anySimpleType char*;
+
+  string char*;
+  normalizedString char*;
+  token char*;
+  Name char*;
+  NMTOKEN char*;
+  NCName char*;
+  ID char*;
+  IDREF char*;
+  language char*;
+  anyURI char*;
+
+  QName xml_schema::qname*;
+}
+  
+ +

For more information about the mapping of the built-in XML Schema types + to C++ types refer to Chapter 6, "Built-In XML Schema Type + Parsers". The last predefined rule maps anything that wasn't + mapped by previous rules to void:

+ +
+namespace .*
+{
+  .* void void;
+}
+  
+ + +

When you provide your own type maps with the + --type-map option, they are evaluated first. This + allows you to selectively override any + of the predefined rules. Note also that if you change the mapping + of a built-in XML Schema type then it becomes your responsibility + to provide the corresponding parser skeleton and implementation + in the xml_schema namespace. You can include the + custom definitions into the generated header file using the + --hxx-prologue-* options.

+ +

4.3 Parser Implementations

+ +

With the knowledge from the previous section, we can proceed + with creating a type map that maps types in the people.xsd + schema to our object model classes in + people.hxx. In fact, we already have the beginning + of our type map file in people.map. Let's extend + it with the rest of the types:

+ +
+include "people.hxx";
+
+gender ::gender ::gender;
+person ::person;
+people ::people;
+  
+ +

A few things to note about this type map. We did not + provide the argument types for person and + people because the default constant reference is + exactly what we need. We also did not provide any mappings + for built-in XML Schema types string and + short because they are handled by the predefined + rules and we are happy with the result. Note also that + all C++ types are fully qualified. This is done to avoid + potential name conflicts in the generated code. Now we can + recompile our schema and move on to implementing the parsers:

+ +
+$ xsde cxx-parser --type-map people.map people.xsd
+  
+ +

Here is the implementation of our three parsers in full. One + way to save typing when implementing your own parsers is + to open the generated code and copy the signatures of parser + callbacks into your code. Or you could always auto generate the + sample implementations and fill them with your code.

+ +
+#include "people-pskel.hxx"
+
+class gender_pimpl: public gender_pskel
+{
+public:
+  gender_pimpl ()
+    : gender_pskel (&base_impl_)
+  {
+  }
+
+  virtual ::gender
+  post_gender ()
+  {
+    return post_string () == "male" ? male : female;
+  }
+
+private:
+  xml_schema::string_pimpl base_impl_;
+};
+
+class person_pimpl: public person_pskel
+{
+public:
+  virtual void
+  first_name (const std::string& f)
+  {
+    first_ = f;
+  }
+
+  virtual void
+  last_name (const std::string& l)
+  {
+    last_ = l;
+  }
+
+  virtual void
+  gender (::gender g)
+  {
+    gender_ = g;
+  }
+
+  virtual void
+  age (short a)
+  {
+    age_ = a;
+  }
+
+  virtual ::person
+  post_person ()
+  {
+    return ::person (first_, last_, gender_, age_);
+  }
+
+private:
+  std::string first_;
+  std::string last_;
+  ::gender gender_;
+  short age_;
+};
+
+class people_pimpl: public people_pskel
+{
+public:
+  virtual void
+  person (const ::person& p)
+  {
+    people_.push_back (p);
+  }
+
+  virtual ::people
+  post_people ()
+  {
+    ::people r;
+    r.swap (people_);
+    return r;
+  }
+
+private:
+  ::people people_;
+};
+  
+ +

This code fragment should look familiar by now. Just note that + all the post_*() callbacks now have return types instead + of void. Here is the implementation of the test + driver for this example:

+ +
+#include <iostream>
+
+using namespace std;
+
+int
+main (int argc, char* argv[])
+{
+  // Construct the parser.
+  //
+  xml_schema::short_pimpl short_p;
+  xml_schema::string_pimpl string_p;
+
+  gender_pimpl gender_p;
+  person_pimpl person_p;
+  people_pimpl people_p;
+
+  person_p.parsers (string_p, string_p, gender_p, short_p);
+  people_p.parsers (person_p);
+
+  // Parse the document to obtain the object model.
+  //
+  xml_schema::document_pimpl doc_p (people_p, "people");
+
+  people_p.pre ();
+  doc_p.parse (argv[1]);
+  people ppl = people_p.post_people ();
+
+  // Print the object model.
+  //
+  for (people::iterator i (ppl.begin ()); i != ppl.end (); ++i)
+  {
+    cout << "first:  " << i->first () << endl
+         << "last:   " << i->last () << endl
+         << "gender: " << (i->gender () == male ? "male" : "female") << endl
+         << "age:    " << i->age () << endl
+         << endl;
+  }
+}
+  
+ +

The parser creation and assembly part is exactly the same as in + the previous chapter. The parsing part is a bit different: + post_people() now has a return value which is the + complete object model. We store it in the + ppl variable. The last bit of the code simply iterates + over the people vector and prints the information + for each person. We save the last two code fragments to + driver.cxx and proceed to compile and test + our new application:

+ + +
+$ c++ -I.../libxsde -c driver.cxx people-pskel.cxx
+$ c++ -o driver driver.o people-pskel.o .../libxsde/xsde/libxsde.a
+$ ./driver people.xml
+first:  John
+last:   Doe
+gender: male
+age:    32
+
+first:  Jane
+last:   Doe
+gender: female
+age:    28
+  
+ + + + + +

5 Mapping Configuration

+ +

The Embedded C++/Parser mapping has a number of configuration + parameters that determine the overall properties and behavior + of the generated code, such as the use of Standard Template + Library (STL), Input/Output Stream Library (iostream), C++ + exceptions, XML Schema validation, 64-bit integer types, parser + implementation reuse styles, and support for XML Schema polymorphism. + Previous chapters assumed that the use of STL, iostream, C++ + exceptions, and XML Schema validation were enabled. + This chapter will discuss the changes in the Embedded C++/Parser + programming model that result from the changes to these configuration + parameters. A complete example that uses the minimal mapping + configuration is presented at the end of this chapter.

+ +

In order to enable or disable a particular feature, the corresponding + configuration parameter should be set accordingly in the XSD/e runtime + library as well as specified during schema compilation with the XSD/e + command line options as described in the + XSD/e + Compiler Command Line Manual. +

+ +

While the XML documents can use various encodings, the Embedded + C++/Parser mapping always delivers character data to the application + in the same encoding. The application encoding can either be UTF-8 + (default) or ISO-8859-1. To select a particular encoding, configure + the XSD/e runtime library accordingly and pass the --char-encoding + option to the XSD/e compiler when translating your schemas.

+ +

When using ISO-8859-1 as the application encoding, XML documents + being parsed may contain characters with Unicode values greater + than 0xFF which are unrepresentable in the ISO-8859-1 encoding. + By default, in such situations parsing will terminate with + an error. However, you can suppress the error by providing a + replacement character that should be used instead of + unrepresentable characters, for example:

+ +
+xml_schema::iso8859_1::unrep_char ('?');
+  
+ +

To revert to the default behavior, set the replacement character + to '\0'.

+ +

The Embedded C++/Parser mapping includes built-in support for XML + documents encoded in UTF-8, UTF-16, ISO-8859-1, and US-ASCII. + Other encodings can be supported by providing application-specific + decoder functions.

+ +

5.1 Standard Template Library

+ +

To disable the use of STL you will need to configure the XSD/e + runtime without support for STL as well as pass the + --no-stl option to the XSD/e compiler when + translating your schemas. When STL is disabled, all string-based + XML Schema types are mapped to C-style char* instead + of std::string, as described in + Section 4.2, "Type Map File Format". The + following code fragment shows changes in the + signatures of first_name() and last_name() + callbacks from the person record example.

+ +
+class person_pskel
+{
+public:
+  virtual void
+  first_name (char*);
+
+  virtual void
+  last_name (char*);
+
+  ...
+};
+  
+ +

Note that it is your responsibility to eventually release the memory + associated with these strings using operator delete[]. +

+ +

5.2 Input/Output Stream Library

+ +

To disable the use of iostream you will need to configure the + XSD/e runtime library without support for iostream as well as + pass the --no-iostream option to the XSD/e compiler + when translating your schemas. When iostream is disabled, the + following two parse() functions in the + xml_schema::document_pimpl class become unavailable:

+ +
+  void
+  parse (const std::string& file);
+
+  void
+  parse (std::istream&);
+  
+ +

Leaving you with only one function in the form:

+ +
+  void
+  parse (const void* data, size_t size, bool last);
+  
+ +

See Section 7.1, "Document Parser" + for more information on the semantics of these functions.

+ +

5.3 C++ Exceptions

+ +

To disable the use of C++ exceptions, you will need to configure + the XSD/e runtime without support for exceptions as well as pass + the --no-exceptions option to the XSD/e compiler + when translating your schemas. When C++ exceptions are disabled, + the error conditions are indicated with error codes instead of + exceptions, as described in Section 7.3, + "Error Codes". +

+ +

5.4 XML Schema Validation

+ +

To disable support for XML Schema validation, you will need to + configure the XSD/e runtime accordingly as well as pass + the --suppress-validation option to the XSD/e compiler + when translating your schemas. Disabling XML Schema validation + allows to further increase the parsing performance and + reduce footprint in cases where XML instances are known to be + valid. +

+ +

5.5 64-bit Integer Type

+ +

By default the 64-bit long and unsignedLong + XML Schema built-in types are mapped to the 64-bit long long + and unsigned long long fundamental C++ types. To + disable the use of these types in the mapping you will need to + configure the XSD/e runtime accordingly as well as pass + the --no-long-long option to the XSD/e compiler + when translating your schemas. When the use of 64-bit integral + C++ types is disabled the long and + unsignedLong XML Schema built-in types are mapped + to long and unsigned long fundamental + C++ types.

+ +

5.6 Parser Reuse

+ +

When one type in XML Schema inherits from another, it is + often desirable to be able to reuse the parser implementation + corresponding to the base type in the parser implementation + corresponding to the derived type. XSD/e provides support + for two parser reuse styles: the so-called mixin + (generated when the --reuse-style-mixin option + is specified) and tiein (generated by default) styles.

+ +

The compiler can also be instructed not to generate any support + for parser reuse with the --reuse-style-none option. + This is mainly useful to further reduce the generated code size + when your vocabulary does not use inheritance or when you plan + to implement each parser from scratch. Note also that the + XSD/e runtime should be configured in accordance with the + parser reuse style used in the generated code. The remainder + of this section discusses the mixin and tiein parser reuse + styles in more detail.

+ + +

To provide concrete examples for each reuse style we will use the + following schema fragment:

+ +
+<xs:complexType name="person">
+  <xs:sequence>
+    <xs:element name="first-name" type="xs:string"/>
+    <xs:element name="last-name" type="xs:string"/>
+    <xs:element name="age" type="xs:short"/>
+  </xs:sequence>
+</xs:complexType>
+
+<xs:complexType name="emplyee">
+  <complexContent>
+    <extension base="person">
+      <xs:sequence>
+        <xs:element name="position" type="xs:string"/>
+        <xs:element name="salary" type="xs:unsignedLong"/>
+      </xs:sequence>
+    </extension>
+  </complexContent>
+</xs:complexType>
+  
+ +

The mixin parser reuse style uses the C++ mixin idiom that + relies on multiple and virtual inheritance. Because + virtual inheritance can result in a significant object + code size increase, this reuse style should be considered + when such an overhead is acceptable and/or the vocabulary + consists of only a handful of types. When the mixin reuse + style is used, the generated parser skeletons use virtual + inheritance, for example:

+ +
+class person_pskel: public virtual parser_complex_content
+{
+  ...
+};
+
+class employee_pskel: public virtual person_pskel
+{
+  ...
+};
+  
+ + +

When you implement the base parser you also need to use + virtual inheritance. The derived parser is implemented + by inheriting from both the derived parser skeleton and + the base parser implementation (that is, mixing in + the base parser implementation), for example:

+ +
+class person_pimpl: public virtual person_pskel
+{
+  ...
+};
+
+class employee_pimpl: public employee_pskel,
+                      public person_pimpl
+{
+  ...
+};
+  
+ + +

The tiein parser reuse style uses delegation and normally + results in a significantly smaller object code while being + almost as convenient to use as the mixin style. When the + tiein reuse style is used, the generated derived parser + skeleton declares a constructor which allows you to specify + the implementation of the base parser:

+ +
+class person_pskel: public parser_complex_content
+{
+  ...
+};
+
+class employee_pskel: public person_pskel
+{
+public:
+  employee_pskel (person_pskel* base_impl)
+
+  ...
+};
+  
+ +

If you pass the implementation of the base parser to this + constructor then the generated code will transparently + forward all the callbacks corresponding to the base parser + skeleton to this implementation. You can also pass + 0 to this constructor in which case you will + need to implement the derived parser from scratch. The + following example shows how we could implement the + person and employee parsers + using the tiein style:

+ +
+class person_pimpl: public person_pskel
+{
+  ...
+};
+
+class employee_pimpl: public employee_pskel
+{
+public:
+  employee_pimpl ()
+    : employee_pskel (&base_impl_)
+  {
+  }
+
+  ...
+
+private:
+  person_pimpl base_impl_;
+};
+  
+ +

Note that you cannot use the tied in base parser + instance (base_impl_ in the above code) for + parsing anything except the derived type.

+ +

The ability to override the base parser callbacks in the + derived parser is also available in the tiein style. For + example, the following code fragment shows how we can + override the age() callback if we didn't + like the implementation provided by the base parser:

+ +
+class employee_pimpl: public employee_pskel
+{
+public:
+  employee_pimpl ()
+    : employee_pskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  age (short a)
+  {
+    ...
+  }
+
+  ...
+
+private:
+  person_pimpl base_impl_;
+};
+  
+ +

In the above example the age element will be + handled by emplyee_pimpl while the first-name + and last-name callbacks will still go to + base_impl_.

+ +

It is also possible to inherit from the base parser implementation + instead of declaring it as a member variable. This can be useful + if you need to access protected members in the base implementation + or need to override a virtual function that is not part of + the parser skeleton interface. Note, however, that in this case + you will need to resolve a number of ambiguities with explicit + qualifications or using-declarations. For example:

+ + +
+class person_pimpl: public person_pskel
+{
+  ...
+protected:
+  virtual person*
+  create ()
+  {
+    return new person ();
+  }
+};
+
+class employee_pimpl: public employee_pskel,
+                      public person_pimpl
+{
+public:
+  employee_pimpl ()
+    : employee_pskel (static_cast<person_pimpl*> (this))
+  {
+  }
+
+  // Resolve ambiguities.
+  //
+  using emplyee_pskel::parsers;
+
+  ...
+
+protected:
+  virtual employee*
+  create ()
+  {
+    return new employee ();
+  }
+};
+  
+ + +

5.7 Support for Polymorphism

+ +

By default the XSD/e compiler generates non-polymorphic code. If your + vocabulary uses XML Schema polymorphism in the form of xsi:type + and/or substitution groups, then you will need to configure the XSD/e + runtime with support for polymorphism, compile your schemas with the + --generate-polymorphic option to produce polymorphism-aware + code, as well as pass true as the last argument to the + xml_schema::document_pimpl's constructors. If some of your + schemas do not require support for polymorphism then you can compile + them with the --runtime-polymorphic option and still + use the XSD/e runtime configured with polymorphism support. +

+ +

When using the polymorphism-aware generated code, you can specify + several parsers for a single element by passing a parser map + instead of an individual parser to the parser connection function + for the element. One of the parsers will then be looked up and used + depending on the xsi:type attribute value or an element + name from a substitution group. Consider the following schema as an + example:

+ +
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="person">
+    <xs:sequence>
+      <xs:element name="name" type="xs:string"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <!-- substitution group root -->
+  <xs:element name="person" type="person"/>
+
+  <xs:complexType name="superman">
+    <xs:complexContent>
+      <xs:extension base="person">
+        <xs:attribute name="can-fly" type="xs:boolean"/>
+      </xs:extension>
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:element name="superman"
+              type="superman"
+              substitutionGroup="person"/>
+
+  <xs:complexType name="batman">
+    <xs:complexContent>
+      <xs:extension base="superman">
+        <xs:attribute name="wing-span" type="xs:unsignedInt"/>
+      </xs:extension>
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:element name="batman"
+              type="batman"
+              substitutionGroup="superman"/>
+
+  <xs:complexType name="supermen">
+    <xs:sequence>
+      <xs:element ref="person" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="supermen" type="supermen"/>
+
+</xs:schema>
+  
+ +

Conforming XML documents can use the superman + and batman types in place of the person + type either by specifying the type with the xsi:type + attributes or by using the elements from the substitution + group, for instance:

+ + +
+<supermen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+
+  <person>
+    <name>John Doe</name>
+  </person>
+
+  <superman can-fly="false">
+    <name>James "007" Bond</name>
+  </superman>
+
+  <superman can-fly="true" wing-span="10" xsi:type="batman">
+    <name>Bruce Wayne</name>
+  </superman>
+
+</supermen>
+  
+ +

To print the data stored in such XML documents we can implement + the parsers as follows:

+ +
+class person_pimpl: public person_pskel
+{
+public:
+  virtual void
+  pre ()
+  {
+    cout << "starting to parse person" << endl;
+  }
+
+  virtual void
+  name (const std::string& v)
+  {
+    cout << "name: " << v << endl;
+  }
+
+  virtual void
+  post_person ()
+  {
+    cout << "finished parsing person" << endl;
+  }
+};
+
+class superman_pimpl: public superman_pskel
+{
+public:
+  superman_pimpl ()
+    : superman_pskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  pre ()
+  {
+    cout << "starting to parse superman" << endl;
+  }
+
+  virtual void
+  can_fly (bool v)
+  {
+    cout << "can-fly: " << v << endl;
+  }
+
+  virtual void
+  post_person ()
+  {
+    post_superman ();
+  }
+
+  virtual void
+  post_superman ()
+  {
+    cout << "finished parsing superman" << endl
+  }
+
+private:
+  person_pimpl base_impl_;
+};
+
+class batman_pimpl: public batman_pskel
+{
+public:
+  batman_pimpl ()
+    : batman_pskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  pre ()
+  {
+    cout << "starting to parse batman" << endl;
+  }
+
+  virtual void
+  wing_span (unsigned int v)
+  {
+    cout << "wing-span: " << v << endl;
+  }
+
+  virtual void
+  post_person ()
+  {
+    post_superman ();
+  }
+
+  virtual void
+  post_superman ()
+  {
+    post_batman ();
+  }
+
+  virtual void
+  post_batman ()
+  {
+    cout << "finished parsing batman" << endl;
+  }
+
+private:
+  superman_pimpl base_impl_;
+};
+  
+ +

Note that because the derived type parsers (superman_pskel + and batman_pskel) are called via the person_pskel + interface, we have to override the post_person() virtual + function in superman_pimpl and batman_pimpl + to call post_superman() and the post_superman() + virtual function in batman_pimpl to call + post_batman() (when the mixin parser reuse style is used + it is not necessary to override post_person() + in batman_pimpl since the suitable implementation + is inherited from superman_pimpl).

+ +

The following code fragment shows how to connect the parsers together. + Notice that for the person element in the supermen_p + parser we specify a parser map instead of a specific parser and we pass + true as the last argument to the document parser constructor + to indicate that we are parsing potentially-polymorphic XML documents:

+ +
+int
+main (int argc, char* argv[])
+{
+  // Construct the parser.
+  //
+  xml_schema::string_pimpl string_p;
+  xml_schema::boolean_pimpl boolean_p;
+  xml_schema::unsigned_int_pimpl unsigned_int_p;
+
+  person_pimpl person_p;
+  superman_pimpl superman_p;
+  batman_pimpl batman_p;
+
+  xml_schema::parser_map_impl person_map (5); // 5 hashtable buckets
+  supermen_pimpl supermen_p;
+
+  person_p.parsers (string_p);
+  superman_p.parsers (string_p, boolean_p);
+  batman_p.parsers (string_p, boolean_p, unsigned_int_p);
+
+  // Here we are specifying several parsers that can be used to
+  // parse the person element.
+  //
+  person_map.insert (person_p);
+  person_map.insert (superman_p);
+  person_map.insert (batman_p);
+
+  supermen_p.person_parser (person_map);
+
+  // Parse the XML document. The last argument to the document's
+  // constructor indicates that we are parsing polymorphic XML
+  // documents.
+  //
+  xml_schema::document_pimpl doc_p (supermen_p, "supermen", true);
+
+  supermen_p.pre ();
+  doc_p.parse (argv[1]);
+  supermen_p.post_supermen ();
+}
+  
+ +

When polymorphism-aware code is generated, each element's + *_parser() function is overloaded to also accept + an object of the xml_schema::parser_map type. + For example, the supermen_pskel class from the + above example looks like this:

+ +
+class supermen_pskel: public xml_schema::parser_complex_content
+{
+public:
+
+  ...
+
+  // Parser construction API.
+  //
+  void
+  parsers (person_pskel&);
+
+  // Individual element parsers.
+  //
+  void
+  person_parser (person_pskel&);
+
+  void
+  person_parser (xml_schema::parser_map&);
+
+  ...
+};
+  
+ +

Note that you can specify both the individual (static) parser and + the parser map. The individual parser will be used when the static + element type and the dynamic type of the object being parsed are + the same. This is the case, for example, when there is no + xsi:type attribute and the element hasn't been + substituted. Because the individual parser for an element is + cached and no map lookup is necessary, it makes sense to specify + both the individual parser and the parser map when most of the + objects being parsed are of the static type and optimal + performance is important. The following code fragment shows + how to change the above example to set both the individual + parser and the parser map:

+ +
+int
+main (int argc, char* argv[])
+{
+  ...
+
+  // Here we are specifying several parsers that can be used to
+  // parse the person element.
+  //
+  person_map.insert (superman_p);
+  person_map.insert (batman_p);
+
+  supermen_p.person_parser (person_p);
+  supermen_p.person_parser (person_map);
+
+  ...
+}
+  
+ + +

The xml_schema::parser_map interface and the + xml_schema::parser_map_impl default implementation + are presented below:

+ +
+namespace xml_schema
+{
+  class parser_map
+  {
+  public:
+    virtual parser_base*
+    find (const char* type) const = 0;
+
+    virtual void
+    reset () const = 0;
+  };
+
+  class parser_map_impl: public parser_map
+  {
+  public:
+    parser_map_impl (size_t buckets);
+
+    void
+    insert (parser_base&);
+
+    virtual parser_base*
+    find (const char* type) const;
+
+    virtual void
+    reset () const;
+
+  private:
+    parser_map_impl (const parser_map_impl&);
+
+    parser_map_impl&
+    operator= (const parser_map_impl&);
+
+    ...
+  };
+}
+  
+ +

The type argument in the find() virtual + function is the type name and namespace from the xsi:type attribute + (the namespace prefix is resolved to the actual XML namespace) + or the type of an element from the substitution group in the form + "<name> <namespace>" with the space and the + namespace part absent if the type does not have a namespace. + You can obtain a parser's dynamic type in the same format + using the _dynamic_type() function. The static + type can be obtained by calling the static _static_type() + function, for example person_pskel::_static_type(). + Both functions return a C string (const char*) which + is valid for as long as the application is running. The + reset() virtual function is used to reset + the parsers contained in the map (as opposed to resetting or + clearing the map itself). For more information on parser + resetting refer to Section 7.4, "Reusing Parsers + after an Error". The following example shows how we can + implement our own parser map using std::map:

+ + +
+#include <map>
+#include <string>
+
+class parser_map: public xml_schema::parser_map
+{
+public:
+ void
+ insert (xml_schema::parser_base& p)
+ {
+   map_[p._dynamic_type ()] = &p;
+ }
+
+ virtual xml_schema::parser_base*
+ find (const char* type) const
+ {
+   map::const_iterator i = map_.find (type);
+   return i != map_.end () ? i->second : 0;
+ }
+
+ virtual void
+ reset () const
+ {
+   for (map::const_iterator i (map_.begin ()), e (map_.end ());
+        i != e; ++i)
+   {
+     xml_schema::parser_base* p = i->second;
+     p->_reset ();
+   }
+ }
+
+private:
+  typedef std::map<std::string, xml_schema::parser_base*> map;
+  map map_;
+};
+  
+ +

The XSD/e runtime provides the default implementation for the + xml_schema::parser_map interface, + xml_schema::parser_map_impl, which is a hashmap. + It requires that you specify the number of buckets it will contain + and it does not support automatic table resizing. To obtain good + performance the elements to buckets ratio should be between 0.7 and + 0.9. It is also recommended to use prime numbers for bucket counts: + 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, + 196613, 393241. +

+ +

If C++ exceptions are disabled (Section 5.3, + "C++ Exceptions"), the xml_schema::parser_map_impl + class has the following additional error querying API. It can be used + to detect the out of memory errors after calls to the + parser_map_impl's constructor and insert() + function.

+ +
+namespace xml_schema
+{
+  class parser_map_impl: public parser_map
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    error
+    _error () const;
+
+    ...
+  };
+}
+  
+ +

To support polymorphic parsing the XSD/e runtime and generated code + maintain a number of hashmaps that contain substitution and, if + XML Schema validation is enabled (Section 5.4, + "XML Schema Validation"), inheritance information. Because + the number of elements in these hashmaps depends on the schemas + being compiled and thus is fairly static, these hashmaps do not + perform automatic table resizing and instead the number of buckets + is specified when the XSD/e runtime is configured. To obtain good + performance the elements to buckets ratio in these hashmaps should + be between 0.7 and 0.9. The recommended way to ensure this range + is to add diagnostics code to your application as shown in the + following example:

+ +
+int
+main ()
+{
+  // Check that the load in substitution and inheritance hashmaps
+  // is not too high.
+  //
+#ifndef NDEBUG
+  float load = xml_schema::parser_smap_elements ();
+  load /= xml_schema::parser_smap_buckets ();
+
+  if (load > 0.8)
+  {
+    cerr << "substitution hashmap load is " << load << endl;
+    cerr << "time to increase XSDE_PARSER_SMAP_BUCKETS" << endl;
+  }
+
+  load = xml_schema::parser_imap_elements ();
+  load /= xml_schema::parser_imap_buckets ();
+
+  if (load > 0.8)
+  {
+    cerr << "inheritance hashmap load is " << load << endl;
+    cerr << "time to increase XSDE_PARSER_IMAP_BUCKETS" << endl;
+  }
+#endif
+
+  ...
+}
+  
+ +

Most of the code presented in this section is taken from the + polymorphism example which can be found in the + examples/cxx/parser/ directory of the XSD/e distribution. + Handling of xsi:type and substitution groups when used + on root elements requires a number of special actions as shown in + the polyroot example.

+ +

5.8 Custom Allocators

+ +

By default the XSD/e runtime and generated code use + the standard operators new and delete + to manage dynamic memory. However, it is possible to instead + use custom allocator functions provided by your application. + To achieve this, configure the XSD/e runtime library to use + custom allocator functions as well as pass the + --custom-allocator option to the XSD/e compiler + when translating your schemas. The signatures of the custom + allocator functions that should be provided by your application + are listed below. Their semantics should be equivalent to the + standard C malloc(), realloc(), and + free() functions.

+ +
+extern "C" void*
+xsde_alloc (size_t);
+
+extern "C" void*
+xsde_realloc (void*, size_t);
+
+extern "C" void
+xsde_free (void*);
+  
+ +

Note also that when custom allocators are enabled, any + dynamically-allocated object of which the XSD/e runtime + or generated code assume ownership should be allocated + using the custom allocation function. Similarly, if your + application assumes ownership of any dynamically-allocated + object returned by the XSD/e runtime or the generated code, + then such an object should be disposed of using the custom + deallocation function. To help with these tasks the generated + xml_schema namespace defines the following two + helper functions and, if C++ exceptions are enabled, automatic + pointer class:

+ +
+namespace xml_schema
+{
+  void*
+  alloc (size_t);
+
+  void
+  free (void*);
+
+  struct alloc_guard
+  {
+    alloc_guard (void*);
+    ~alloc_guard ();
+
+    void*
+    get () const;
+
+    void
+    release ();
+
+  private:
+    ...
+  };
+}
+  
+ +

If C++ exceptions are disabled, these functions are equivalent + to xsde_alloc() and xsde_free(). + If exceptions are enabled, xml_schema::alloc() + throws std::bad_alloc on memory allocation failure.

+ +

The following code fragment shows how to create and destroy a + dynamically-allocated object with custom allocators when C++ + exceptions are disabled:

+ +
+void* v = xml_schema::alloc (sizeof (type));
+
+if (v == 0)
+{
+  // Handle out of memory condition.
+}
+
+type* x = new (v) type (1, 2);
+
+...
+
+if (x)
+{
+  x->~type ();
+  xml_schema::free (x);
+}
+  
+ +

The equivalent code fragment for configurations with C++ exceptions + enabled is shown below:

+ +
+xml_schema::alloc_guard g (xml_schema::alloc (sizeof (type)));
+type* x = new (g.get ()) type (1, 2);
+g.release ();
+
+...
+
+if (x)
+{
+  x->~type ();
+  xml_schema::free (x);
+}
+  
+ +

5.9 A Minimal Example

+ +

The following example is a re-implementation of the person + records example presented in Chapter 3, + "Parser Skeletons". It is intended to work + without STL, iostream, and C++ exceptions. It can be found in + the examples/cxx/parser/minimal/ directory of the + XSD/e distribution. The people.xsd schema is + compiled with the --no-stl, --no-iostream, + and --no-exceptions options. The following listing + presents the implementation of parser skeletons and the test + driver in full.

+ +
+#include <stdio.h>
+
+#include "people-pskel.hxx"
+
+class gender_pimpl: public gender_pskel
+{
+public:
+  gender_pimpl ()
+    : gender_pskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  post_gender ()
+  {
+    char* s = post_string ();
+    printf ("gender: %s\n", s);
+    delete[] s;
+  }
+
+private:
+  xml_schema::string_pimpl base_impl_;
+};
+
+class person_pimpl: public person_pskel
+{
+public:
+  virtual void
+  first_name (char* n)
+  {
+    printf ("first: %s\n", n);
+    delete[] n;
+  }
+
+  virtual void
+  last_name (char* n)
+  {
+    printf ("last: %s\n", n);
+    delete[] n;
+  }
+
+  virtual void
+  age (short a)
+  {
+    printf ("age: %hd\n", a);
+  }
+};
+
+class people_pimpl: public people_pskel
+{
+public:
+  virtual void
+  person ()
+  {
+    // Add an extra newline after each person record.
+    //
+    printf ("\n");
+  }
+};
+
+int
+main (int argc, char* argv[])
+{
+  // Construct the parser.
+  //
+  xml_schema::short_pimpl short_p;
+  xml_schema::string_pimpl string_p;
+
+  gender_pimpl gender_p;
+  person_pimpl person_p;
+  people_pimpl people_p;
+
+  person_p.parsers (string_p, string_p, gender_p, short_p);
+  people_p.parsers (person_p);
+
+  // Open the file.
+  //
+  FILE* f = fopen (argv[1], "rb");
+
+  if (f == 0)
+  {
+    fprintf (stderr, "%s: unable to open\n", argv[1]);
+    return 1;
+  }
+
+  // Parse.
+  //
+  typedef xml_schema::parser_error error;
+  error e;
+  bool io_error = false;
+
+  do
+  {
+    xml_schema::document_pimpl doc_p (people_p, "people");
+    if (e = doc_p._error ())
+      break;
+
+    people_p.pre ();
+    if (e = people_p._error ())
+      break;
+
+    char buf[4096];
+    do
+    {
+      size_t s = fread (buf, 1, sizeof (buf), f);
+
+      if (s != sizeof (buf) && ferror (f))
+      {
+        io_error = true;
+        break;
+      }
+
+      doc_p.parse (buf, s, feof (f) != 0);
+      e = doc_p._error ();
+
+    } while (!e && !feof (f));
+
+    if (io_error || e)
+      break;
+
+    people_p.post_people ();
+    e = people_p._error ();
+
+  } while (false);
+
+  fclose (f);
+
+  // Handle errors.
+  //
+
+  if (io_error)
+  {
+    fprintf (stderr, "%s: read failure\n", argv[1]);
+    return 1;
+  }
+
+  if (e)
+  {
+    switch (e.type ())
+    {
+    case error::sys:
+      {
+        fprintf (stderr, "%s: %s\n", argv[1], e.sys_text ());
+        break;
+      }
+    case error::xml:
+      {
+        fprintf (stderr, "%s:%lu:%lu: %s\n",
+                 argv[1], e.line (), e.column (), e.xml_text ());
+        break;
+      }
+    case error::schema:
+      {
+        fprintf (stderr, "%s:%lu:%lu: %s\n",
+                 argv[1], e.line (), e.column (), e.schema_text ());
+        break;
+      }
+    case error::app:
+      {
+        fprintf (stderr, "%s:%lu:%lu: application error %d\n",
+                 argv[1], e.line (), e.column (), e.app_code ());
+        break;
+      }
+    default:
+      break;
+    }
+    return 1;
+  }
+  return 0;
+}
+  
+ + + + + +

6 Built-In XML Schema Type Parsers

+ +

The XSD/e runtime provides parser implementations for all built-in + XML Schema types as summarized in the following table. Declarations + for these types are automatically included into each generated + header file. As a result you don't need to include any headers + to gain access to these parser implementations.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XML Schema typeParser implementation in the xml_schema namespaceParser return type
anyType and anySimpleType types
anyTypeany_type_pimplvoid
anySimpleTypeany_simple_type_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
fixed-length integral types
bytebyte_pimplsigned char
unsignedByteunsigned_byte_pimplunsigned char
shortshort_pimplshort
unsignedShortunsigned_short_pimplunsigned short
intint_pimplint
unsignedIntunsigned_int_pimplunsigned int
longlong_pimpllong long or long
+ Section 5.5, "64-bit Integer Type"
unsignedLongunsigned_long_pimplunsigned long long or + unsigned long
+ Section 5.5, "64-bit Integer Type"
arbitrary-length integral types
integerinteger_pimpllong
nonPositiveIntegernon_positive_integer_pimpllong
nonNegativeIntegernon_negative_integer_pimplunsigned long
positiveIntegerpositive_integer_pimplunsigned long
negativeIntegernegative_integer_pimpllong
boolean types
booleanboolean_pimplbool
fixed-precision floating-point types
floatfloat_pimplfloat
doubledouble_pimpldouble
arbitrary-precision floating-point types
decimaldecimal_pimpldouble
string-based types
stringstring_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
normalizedStringnormalized_string_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
tokentoken_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
Namename_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
NMTOKENnmtoken_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
NCNamencname_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
languagelanguage_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
qualified name
QNameqname_pimplxml_schema::qname or xml_schema::qname*
+ Section 6.1, "QName Parser"
ID/IDREF types
IDid_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
IDREFidref_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
list types
NMTOKENSnmtokens_pimplxml_schema::string_sequence*
Section + 6.2, "NMTOKENS and IDREFS Parsers"
IDREFSidrefs_pimplxml_schema::string_sequence*
Section + 6.2, "NMTOKENS and IDREFS Parsers"
URI types
anyURIuri_pimplstd::string or char*
+ Section 5.1, "Standard Template Library"
binary types
base64Binarybase64_binary_pimplxml_schema::buffer*
+ Section 6.3, "base64Binary and + hexBinary Parsers"
hexBinaryhex_binary_pimplxml_schema::buffer*
+ Section 6.3, "base64Binary and + hexBinary Parsers"
date/time types
datedate_pimplxml_schema::date
Section 6.5, + "date Parser"
dateTimedate_time_pimplxml_schema::date_time
Section 6.6, + "dateTime Parser"
durationduration_pimplxml_schema::duration
Section 6.7, + "duration Parser"
gDaygday_pimplxml_schema::gday
Section 6.8, + "gDay Parser"
gMonthgmonth_pimplxml_schema::gmonth
Section 6.9, + "gMonth Parser"
gMonthDaygmonth_day_pimplxml_schema::gmonth_day
Section 6.10, + "gMonthDay Parser"
gYeargyear_pimplxml_schema::gyear
Section 6.11, + "gYear Parser"
gYearMonthgyear_month_pimplxml_schema::gyear_month
Section + 6.12, "gYearMonth Parser"
timetime_pimplxml_schema::time
Section 6.13, + "time Parser"
+ +

6.1 QName Parser

+ +

The return type of the qname_pimpl parser implementation + is either xml_schema::qname when STL is enabled + (Section 5.1, "Standard Template Library") or + xml_schema::qname* when STL is disabled. The + qname class represents an XML qualified name. When the + return type is xml_schema::qname*, the returned + object is dynamically allocated with operator new + and should eventually be deallocated with operator delete. + With STL enabled, the qname type has the following + interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (const std::string& name);
+    qname (const std::string& prefix, const std::string& name);
+
+    void
+    swap (qname&);
+
+    const std::string&
+    prefix () const;
+
+    std::string&
+    prefix ();
+
+    void
+    prefix (const std::string&);
+
+    const std::string&
+    name () const;
+
+    std::string&
+    name ();
+
+    void
+    name (const std::string&);
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+  
+ +

When STL is disabled and C++ exceptions are enabled + (Section 5.3, "C++ Exceptions"), the + qname type has the following interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (char* name);
+    qname (char* prefix, char* name);
+
+    void
+    swap (qname&);
+
+  private:
+    qname (const qname&);
+
+    qname&
+    operator= (const qname&);
+
+  public:
+    char*
+    prefix ();
+
+    const char*
+    prefix () const;
+
+    void
+    prefix (char*);
+
+    void
+    prefix_copy (const char*);
+
+    char*
+    prefix_detach ();
+
+  public:
+    char*
+    name ();
+
+    const char*
+    name () const;
+
+    void
+    name (char*);
+
+    void
+    name_copy (const char*);
+
+    char*
+    name_detach ();
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+
+ +

The modifier functions and constructors that have the char* + argument assume ownership of the passed strings which should be allocated + with operator new char[] and will be deallocated with + operator delete[] by the qname object. + If you detach the underlying prefix or name strings, then they + should eventually be deallocated with operator delete[]. +

+ +

Finally, if both STL and C++ exceptions are disabled, the + qname type has the following interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (char* name);
+    qname (char* prefix, char* name);
+
+    void
+    swap (qname&);
+
+  private:
+    qname (const qname&);
+
+    qname&
+    operator= (const qname&);
+
+  public:
+    char*
+    prefix ();
+
+    const char*
+    prefix () const;
+
+    void
+    prefix (char*);
+
+    error
+    prefix_copy (const char*);
+
+    char*
+    prefix_detach ();
+
+  public:
+    char*
+    name ();
+
+    const char*
+    name () const;
+
+    void
+    name (char*);
+
+    error
+    name_copy (const char*);
+
+    char*
+    name_detach ();
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+  
+ +

6.2 NMTOKENS and IDREFS Parsers

+ +

The return type of the nmtokens_pimpl and + idrefs_pimpl parser implementations is + xml_schema::string_sequence*. + The returned object is dynamically allocated with operator + new and should eventually be deallocated with + operator delete. With STL and C++ exceptions enabled + (Section 5.1, "Standard Template Library", + Section 5.3, "C++ Exceptions"), the + string_sequence type has the following interface:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    typedef std::string         value_type;
+    typedef std::string*        pointer;
+    typedef const std::string*  const_pointer;
+    typedef std::string&        reference;
+    typedef const std::string&  const_reference;
+
+    typedef size_t              size_type;
+    typedef ptrdiff_t           difference_type;
+
+    typedef std::string*        iterator;
+    typedef const std::string*  const_iterator;
+
+  public:
+    string_sequence ();
+
+    void
+    swap (string_sequence&);
+
+  private:
+    string_sequence (string_sequence&);
+
+    string_sequence&
+    operator= (string_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    std::string&
+    front ();
+
+    const std::string&
+    front () const;
+
+    std::string&
+    back ();
+
+    const std::string&
+    back () const;
+
+    std::string&
+    operator[] (size_t);
+
+    const std::string&
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    push_back (const std::string&);
+
+    iterator
+    insert (iterator, const std::string&);
+
+    void
+    reserve (size_t);
+  };
+
+  bool
+  operator== (const string_sequence&, const string_sequence&);
+
+  bool
+  operator!= (const string_sequence&, const string_sequence&);
+}
+  
+ +

When STL is enabled and C++ exceptions are disabled, the signatures + of the push_back(), insert(), and + reserve() functions change as follows:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (const std::string&);
+
+    error
+    insert (iterator, const std::string&);
+
+    error
+    insert (iterator, const std::string&, iterator& result);
+
+    error
+    reserve (size_t);
+  };
+}
+  
+ +

When STL is disabled and C++ exceptions are enabled, the + string_sequence type has the following interface:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    typedef char*         value_type;
+    typedef char**        pointer;
+    typedef const char**  const_pointer;
+    typedef char*         reference;
+    typedef const char*   const_reference;
+
+    typedef size_t        size_type;
+    typedef ptrdiff_t     difference_type;
+
+    typedef char** iterator;
+    typedef const char* const* const_iterator;
+
+    string_sequence ();
+
+    void
+    swap (string_sequence&);
+
+  private:
+    string_sequence (string_sequence&);
+
+    string_sequence&
+    operator= (string_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    char*
+    front ();
+
+    const char*
+    front () const;
+
+    char*
+    back ();
+
+    const char*
+    back () const;
+
+    char*
+    operator[] (size_t);
+
+    const char*
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    push_back (char*);
+
+    void
+    push_back_copy (const char*);
+
+    iterator
+    insert (iterator, char*);
+
+    void
+    reserve (size_t);
+
+    // Detach a string from the sequence at a given position.
+    // The string pointer at this position in the sequence is
+    // set to 0.
+    //
+    char*
+    detach (iterator);
+  };
+
+  bool
+  operator== (const string_sequence&, const string_sequence&);
+
+  bool
+  operator!= (const string_sequence&, const string_sequence&);
+}
+  
+ +

The push_back() and insert() functions + assume ownership of the passed string which should be allocated + with operator new char[] and will be deallocated + with operator delete[] by the string_sequence + object. These two functions free the passed object if the reallocation + of the underlying sequence buffer fails. The push_back_copy() + function makes a copy of the passed string. + If you detach the underlying element string, then it should + eventually be deallocated with operator delete[].

+ +

When both STL and C++ exceptions are disabled, the signatures + of the push_back(), push_back_copy(), + insert(), and reserve() functions change + as follows:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (char*);
+
+    error
+    push_back_copy (const char*);
+
+    error
+    insert (iterator, char*);
+
+    error
+    insert (iterator, char*, iterator& result);
+
+    error
+    reserve (size_t);
+  };
+}
+  
+ + +

6.3 base64Binary and hexBinary Parsers

+ +

The return type of the base64_binary_pimpl and + hex_binary_pimpl parser implementations is + xml_schema::buffer*. The returned object is + dynamically allocated with operator new and + should eventually be deallocated with operator delete. + With C++ exceptions enabled (Section 5.3, "C++ + Exceptions"), the buffer type has the following + interface:

+ +
+namespace xml_schema
+{
+  class buffer
+  {
+  public:
+    class bounds {}; // Out of bounds exception.
+
+  public:
+    buffer ();
+
+    explicit
+    buffer (size_t size);
+    buffer (size_t size, size_t capacity);
+    buffer (const void* data, size_t size);
+    buffer (const void* data, size_t size, size_t capacity);
+
+    enum ownership_value { assume_ownership };
+
+    // This constructor assumes ownership of the memory passed.
+    //
+    buffer (void* data, size_t size, size_t capacity, ownership_value);
+
+  private:
+    buffer (const buffer&);
+
+    buffer&
+    operator= (const buffer&);
+
+  public:
+    void
+    attach (void* data, size_t size, size_t capacity);
+
+    void*
+    detach ();
+
+    void
+    swap (buffer&);
+
+  public:
+    size_t
+    capacity () const;
+
+    bool
+    capacity (size_t);
+
+  public:
+    size_t
+    size () const;
+
+    bool
+    size (size_t);
+
+  public:
+    const char*
+    data () const;
+
+    char*
+    data ();
+
+    const char*
+    begin () const;
+
+    char*
+    begin ();
+
+    const char*
+    end () const;
+
+    char*
+    end ();
+  };
+
+  bool
+  operator== (const buffer&, const buffer&);
+
+  bool
+  operator!= (const buffer&, const buffer&);
+}
+  
+ +

The last constructor and the attach() member function + make the buffer instance assume the ownership of the + memory block pointed to by the data argument and + eventually release it by calling operator delete(). + The detach() member function detaches and returns the + underlying memory block which should eventually be released by + calling operator delete(). +

+ +

The capacity() and size() modifier functions + return true if the underlying buffer has moved. The + bounds exception is thrown if the constructor or + attach() member function arguments violate the + (size <= capacity) constraint.

+ +

If C++ exceptions are disabled, the buffer type has + the following interface:

+ +
+namespace xml_schema
+{
+  class buffer
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_bounds,
+      error_no_memory
+    };
+
+    buffer ();
+
+  private:
+    buffer (const buffer&);
+
+    buffer&
+    operator= (const buffer&);
+
+  public:
+    error
+    attach (void* data, size_t size, size_t capacity);
+
+    void*
+    detach ();
+
+    void
+    swap (buffer&);
+
+  public:
+    size_t
+    capacity () const;
+
+    error
+    capacity (size_t);
+
+    error
+    capacity (size_t, bool& moved);
+
+  public:
+    size_t
+    size () const;
+
+    error
+    size (size_t);
+
+    error
+    size (size_t, bool& moved);
+
+  public:
+    const char*
+    data () const;
+
+    char*
+    data ();
+
+    const char*
+    begin () const;
+
+    char*
+    begin ();
+
+    const char*
+    end () const;
+
+    char*
+    end ();
+  };
+
+  bool
+  operator== (const buffer&, const buffer&);
+
+  bool
+  operator!= (const buffer&, const buffer&);
+}
+  
+ +

6.4 Time Zone Representation

+ +

The date, dateTime, gDay, + gMonth, gMonthDay, gYear, + gYearMonth, and time XML Schema built-in + types all include an optional time zone component. The following + xml_schema::time_zone base class is used to represent + this information:

+ +
+namespace xml_schema
+{
+  class time_zone
+  {
+  public:
+    time_zone ();
+    time_zone (short hours, short minutes);
+
+    bool
+    zone_present () const;
+
+    void
+    zone_reset ();
+
+    short
+    zone_hours () const;
+
+    void
+    zone_hours (short);
+
+    short
+    zone_minutes () const;
+
+    void
+    zone_minutes (short);
+  };
+
+  bool
+  operator== (const time_zone&, const time_zone&);
+
+  bool
+  operator!= (const time_zone&, const time_zone&);
+}
+  
+ +

The zone_present() accessor function returns true + if the time zone is specified. The zone_reset() modifier + function resets the time zone object to the not specified + state. If the time zone offset is negative then both hours and + minutes components are represented as negative integers.

+ +

6.5 date Parser

+ +

The return type of the date_pimpl parser implementation + is xml_schema::date which represents a year, a day, and a month + with an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 6.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class date: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    date ();
+
+    date (int year, unsigned short month, unsigned short day);
+
+    date (int year, unsigned short month, unsigned short day,
+          short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const date&, const date&);
+
+  bool
+  operator!= (const date&, const date&);
+}
+  
+ +

6.6 dateTime Parser

+ +

The return type of the date_time_pimpl parser implementation + is xml_schema::date_time which represents a year, a month, a day, + hours, minutes, and seconds with an optional time zone. Its interface + is presented below. For more information on the base + xml_schema::time_zone class refer to Section + 6.4, "Time Zone Representation".

+ +
+namespace xml_schema
+{
+  class date_time: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    date_time ();
+
+    date_time (int year, unsigned short month, unsigned short day,
+               unsigned short hours, unsigned short minutes,
+               double seconds);
+
+    date_time (int year, unsigned short month, unsigned short day,
+               unsigned short hours, unsigned short minutes,
+               double seconds, short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+
+    unsigned short
+    hours () const;
+
+    void
+    hours (unsigned short);
+
+    unsigned short
+    minutes () const;
+
+    void
+    minutes (unsigned short);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const date_time&, const date_time&);
+
+  bool
+  operator!= (const date_time&, const date_time&);
+}
+  
+ +

6.7 duration Parser

+ +

The return type of the duration_pimpl parser implementation + is xml_schema::duration which represents a potentially + negative duration in the form of years, months, days, hours, minutes, + and seconds. Its interface is presented below.

+ +
+namespace xml_schema
+{
+  class duration
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    duration ();
+
+    duration (bool negative,
+              unsigned int years, unsigned int months, unsigned int days,
+              unsigned int hours, unsigned int minutes, double seconds);
+
+    bool
+    negative () const;
+
+    void
+    negative (bool);
+
+    unsigned int
+    years () const;
+
+    void
+    years (unsigned int);
+
+    unsigned int
+    months () const;
+
+    void
+    months (unsigned int);
+
+    unsigned int
+    days () const;
+
+    void
+    days (unsigned int);
+
+    unsigned int
+    hours () const;
+
+    void
+    hours (unsigned int);
+
+    unsigned int
+    minutes () const;
+
+    void
+    minutes (unsigned int);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const duration&, const duration&);
+
+  bool
+  operator!= (const duration&, const duration&);
+}
+  
+ + +

6.8 gDay Parser

+ +

The return type of the gday_pimpl parser implementation + is xml_schema::gday which represents a day of the month with + an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 6.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gday: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gday ();
+
+    explicit
+    gday (unsigned short day);
+
+    gday (unsigned short day, short zone_hours, short zone_minutes);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const gday&, const gday&);
+
+  bool
+  operator!= (const gday&, const gday&);
+}
+  
+ +

6.9 gMonth Parser

+ +

The return type of the gmonth_pimpl parser implementation + is xml_schema::gmonth which represents a month of the year + with an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 6.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gmonth: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gmonth ();
+
+    explicit
+    gmonth (unsigned short month);
+
+    gmonth (unsigned short month,
+            short zone_hours, short zone_minutes);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+  };
+
+  bool
+  operator== (const gmonth&, const gmonth&);
+
+  bool
+  operator!= (const gmonth&, const gmonth&);
+}
+  
+ +

6.10 gMonthDay Parser

+ +

The return type of the gmonth_day_pimpl parser implementation + is xml_schema::gmonth_day which represents a day and a month of + the year with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 6.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gmonth_day: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gmonth_day ();
+
+    gmonth_day (unsigned short month, unsigned short day);
+
+    gmonth_day (unsigned short month, unsigned short day,
+                short zone_hours, short zone_minutes);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const gmonth_day&, const gmonth_day&);
+
+  bool
+  operator!= (const gmonth_day&, const gmonth_day&);
+}
+  
+ +

6.11 gYear Parser

+ +

The return type of the gyear_pimpl parser implementation + is xml_schema::gyear which represents a year with + an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 6.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gyear: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gyear ();
+
+    explicit
+    gyear (int year);
+
+    gyear (int year, short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+  };
+
+  bool
+  operator== (const gyear&, const gyear&);
+
+  bool
+  operator!= (const gyear&, const gyear&);
+}
+  
+ +

6.12 gYearMonth Parser

+ +

The return type of the gyear_month_pimpl parser implementation + is xml_schema::gyear_month which represents a year and a month + with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 6.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gyear_month: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gyear_month ();
+
+    gyear_month (int year, unsigned short month);
+
+    gyear_month (int year, unsigned short month,
+                 short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+  };
+
+  bool
+  operator== (const gyear_month&, const gyear_month&);
+
+  bool
+  operator!= (const gyear_month&, const gyear_month&);
+}
+  
+ + +

6.13 time Parser

+ +

The return type of the time_pimpl parser implementation + is xml_schema::time which represents hours, minutes, + and seconds with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 6.4, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class time: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    time ();
+
+    time (unsigned short hours, unsigned short minutes, double seconds);
+
+    time (unsigned short hours, unsigned short minutes, double seconds,
+          short zone_hours, short zone_minutes);
+
+    unsigned short
+    hours () const;
+
+    void
+    hours (unsigned short);
+
+    unsigned short
+    minutes () const;
+
+    void
+    minutes (unsigned short);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const time&, const time&);
+
+  bool
+  operator!= (const time&, const time&);
+}
+  
+ + + + + +

7 Document Parser and Error Handling

+ +

In this chapter we will discuss the xml_schema::document_pimpl + type, the error handling mechanisms provided by the mapping, as well + as how to reuse a parser after an error has occurred.

+ +

There are four categories of errors that can result from running + a parser on an XML instance: system, xml, schema, and application. + The system category contains memory allocation and file/stream + operation errors. The xml category is for XML parsing and + well-formedness checking errors. Similarly, the schema category is + for XML Schema validation errors. Finally, the application category + is for application logic errors that you may want to propagate + from parser implementations to the caller of the parser. +

+ +

The C++/Parser mapping supports two methods of reporting errors: + using C++ exceptions and with error codes. The method used depends + on whether or not you have configured the XSD/e runtime and + the generated code with C++ exceptions enabled, as described + in Section 5.3, "C++ Exceptions".

+ +

7.1 Document Parser

+ +

The xml_schema::document_pimpl parser is a root parser for + the vocabulary. As mentioned in Section 3.4, + "Connecting the Parsers Together", its interface varies depending + on the mapping configuration (Chapter 5, "Mapping + Configuration"). When STL and the iostream library are + enabled, the xml_schema::document_pimpl class has the + following interface:

+ +
+namespace xml_schema
+{
+  class parser_base;
+
+  class document_pimpl
+  {
+  public:
+    document_pimpl (parser_base&,
+                    const char* root_element_name);
+
+    document_pimpl (parser_base&,
+                    const char* root_element_namespace,
+                    const char* root_element_name);
+
+    document_pimpl (parser_base&,
+                    const std::string& root_element_name);
+
+    document_pimpl (parser_base&,
+                    const std::string& root_element_namespace,
+                    const std::string& root_element_name);
+
+
+  public:
+    // Parse a local file. The file is accessed with std::ifstream
+    // in binary mode. The std::ios_base::failure exception is used
+    // to report io errors (badbit and failbit) if exceptions are
+    // enabled. Otherwise error codes are used.
+    //
+    void
+    parse (const char* file);
+
+    void
+    parse (const std::string& file);
+
+    // Parse std::istream. std::ios_base::failure exception is used
+    // to report io errors (badbit and failbit) if exceptions are
+    // enabled. Otherwise error codes are used.
+    //
+    void
+    parse (std::istream&);
+
+    // Parse a chunk of input. You can call this function multiple
+    // times with the last call having the last argument true.
+    //
+    void
+    parse (const void* data, size_t size, bool last);
+
+    // Low-level Expat-specific parsing API.
+    //
+    void
+    parse_begin (XML_Parser);
+
+    void
+    parse_end ();
+  };
+}
+  
+ +

When the use of STL is disabled, the constructors and the parse() + function that use std::string in their signatures + are not available. When the use of iostream is disabled, the + parse() functions that parse a local file and + std::istream are not available.

+ +

When support for XML Schema polymorphism is enabled, the + overloaded document_pimpl constructors have + additional arguments which control polymorphic parsing. + For more information refer to Section 5.7, + "Support for Polymorphism". +

+ +

The first argument to all overloaded constructors is the + parser for the type of the root element. The parser_base + class is the base type for all parser skeletons. The second and + third arguments to the document_pimpl's constructors are + the root element's name and namespace.

+ +

The parse_begin() and parse_end() functions + present a low-level, Expat-specific parsing API for maximum control. + A typical use case would look like this (pseudo-code):

+ +
+xxx_pimpl root_p;
+document_pimpl doc_p (root_p, "root");
+
+root_p.pre ();
+doc_p.parse_begin (xml_parser);
+
+while (more_stuff_to_parse)
+{
+   // Call XML_Parse or XML_ParseBuffer:
+   //
+   if (XML_Parse (...) != XML_STATUS_ERROR)
+     break;
+}
+
+doc_p.parse_end ();
+result_type result (root_p.post_xxx ());
+  
+ +

Note that if your vocabulary use XML namespaces, the + XML_ParserCreateNS() functions should be used to create + the XML parser. Space (XML_Char (' ')) should be used + as a separator (the second argument to XML_ParserCreateNS()). + Furthermore, if XML_Parse or XML_ParseBuffer fail, call + parse_end() to determine the error which is indicated + either via exception or set as an error code. +

+ +

The error handling mechanisms employed by the document_pimpl + parser are described in Section 7.2, "Exceptions" + and Section 7.3, "Error Codes".

+ +

7.2 Exceptions

+ +

When C++ exceptions are used for error reporting, the system + errors are mapped to the standard exceptions. The out of memory + condition is indicated by throwing an instance + of std::bad_alloc. The stream operation errors + are reported by throwing an instance of + std::ios_base::failure.

+ +

The xml and schema errors are reported by throwing the + xml_schema::parser_xml and xml_schema::parser_schema + exceptions, respectively. These two exceptions derive from + xml_schema::parser_exception which, in turn, derives + from std::exception. As a result, you can handle + any error from these two categories by either catching + std::exception, xml_schema::parser_exception, + or individual exceptions. The further down the hierarchy you go + the more detailed error information is available to you. The + following listing shows the definitions of these exceptions:

+ +
+namespace xml_schema
+{
+  class parser_exception: public std::exception
+  {
+  public:
+    unsigned long
+    line () const;
+
+    unsigned long
+    column () const;
+
+    virtual const char*
+    text () const = 0;
+
+    ...
+  };
+
+  std::ostream&
+  operator<< (std::ostream&, const parser_exception&);
+
+
+  typedef <implementation-details> parser_xml_error;
+
+  class parser_xml: public parser_exception
+  {
+  public:
+    parser_xml_error
+    code () const;
+
+    virtual const char*
+    text () const;
+
+    virtual const char*
+    what () const throw ();
+
+    ...
+  };
+
+
+  typedef <implementation-details> parser_schema_error;
+
+  class parser_schema: public parser_exception
+  {
+  public:
+    parser_schema_error
+    code () const;
+
+    virtual const char*
+    text () const;
+
+    virtual const char*
+    what () const throw ();
+
+    ...
+  };
+}
+  
+ +

The parser_xml_error and parser_schema_error + are implementation-specific error code types. The + operator<< defined for the parser_exception + class simply prints the error description as returned by the + text() function. The following example shows + how we can catch these exceptions:

+ +
+int
+main (int argc, char* argv[])
+{
+  try
+  {
+    // Parse argv[1].
+  }
+  catch (const xml_schema::parser_exception& e)
+  {
+    cout << argv[1] << ":" << e.line () << ":" << e.column ()
+         << ": error: " << e.text () << endl;
+    return 1;
+  }
+}
+  
+ +

Finally, for reporting application errors from parsing callbacks, you + can throw any exceptions of your choice. They are propagated to + the caller of the parser without any alterations.

+ +

7.3 Error Codes

+ +

When C++ exceptions are not available, error codes are used to + report error conditions. Each parser skeleton and the root + document_pimpl parser have the following member + function for querying + the error status:

+ +
+xml_schema::parser_error
+_error () const;
+  
+ +

To handle all possible error conditions, you will need to obtain + the error status after calls to: the document_pimpl's + constructor (it performs memory allocations which may fail), the + root parser pre() callback, each call to the parse() + function, and, finally, the call to the root parser + post_*() callback. The definition of + xml_schema::parser_error class is presented below:

+ +
+namespace xml_schema
+{
+  class sys_error
+  {
+  public:
+    enum value
+    {
+      none,
+      no_memory,
+      open_failed,
+      read_failed,
+      write_failed
+    };
+
+    sys_error (value);
+
+    operator value () const;
+
+    static const char*
+    text (value);
+
+    ...
+  };
+
+  typedef <implementation-details> parser_xml_error;
+  typedef <implementation-details> parser_schema_error;
+
+  class parser_error
+  {
+  public:
+    enum error_type
+    {
+      none,
+      sys,
+      xml,
+      schema,
+      app
+    };
+
+    error_type
+    type () const;
+
+    // Line and column are only available for xml, schema, and
+    // app errors.
+    //
+    unsigned long
+    line () const;
+
+    unsigned long
+    column () const;
+
+    // Returns true if there is an error so that you can write
+    // if (p.error ()) or if (error e = p.error ()).
+    //
+    typedef void (error::*bool_convertible) ();
+    operator bool_convertible () const;
+
+    // system
+    //
+    sys_error
+    sys_code () const;
+
+    const char*
+    sys_text () const;
+
+    // xml
+    //
+    parser_xml_error
+    xml_code () const;
+
+    const char*
+    xml_text () const;
+
+    // schema
+    //
+    parser_schema_error
+    schema_code () const;
+
+    const char*
+    schema_text () const;
+
+    // app
+    //
+    int
+    app_code () const;
+
+    ...
+  };
+}
+  
+ +

The parser_xml_error and parser_schema_error + are implementation-specific error code types. The + parser_error class incorporates four categories of errors + which you can query by calling the type() function. + The following example shows how to handle error conditions with + error codes. It is based on the person record example presented + in Chapter 3, "Parser Skeletons".

+ +
+int
+main (int argc, char* argv[])
+{
+  // Construct the parser.
+  //
+  xml_schema::short_pimpl short_p;
+  xml_schema::string_pimpl string_p;
+
+  gender_pimpl gender_p;
+  person_pimpl person_p;
+  people_pimpl people_p;
+
+  person_p.parsers (string_p, string_p, gender_p, short_p);
+  people_p.parsers (person_p);
+
+  // Parse.
+  //
+  using xml_schema::parser_error;
+  parser_error e;
+
+  do
+  {
+    xml_schema::document_pimpl doc_p (people_p, "people");
+    if (e = doc_p._error ())
+      break;
+
+    people_p.pre ();
+    if (e = people_p._error ())
+      break;
+
+    doc_p.parse (argv[1]);
+    if (e = doc_p._error ())
+      break;
+
+    people_p.post_people ();
+    e = people_p._error ();
+
+  } while (false);
+
+  // Handle errors.
+  //
+  if (e)
+  {
+    switch (e.type ())
+    {
+    case parser_error::sys:
+      {
+        cerr << argv[1] << ": error: " << e.sys_text () << endl;
+        break;
+      }
+    case parser_error::xml:
+      {
+        cerr << argv[1] << ":" << e.line () << ":" << e.column ()
+             << ": error: " << e.xml_text () << endl;
+        break;
+      }
+    case parser_error::schema:
+      {
+        cerr << argv[1] << ":" << e.line () << ":" << e.column ()
+             << ": error: " << e.schema_text () << endl;
+        break;
+      }
+    case parser_error::app:
+      {
+        cerr << argv[1] << ":" << e.line () << ":" << e.column ()
+             << ": application error " << e.app_code () << endl;
+        break;
+      }
+    }
+    return 1;
+  }
+}
+  
+ +

The error type for application errors is int with + the value 0 indicated the absence of error. You can + set the application error by calling the _app_error() + function inside a parser callback. For example, if it was invalid to + have a person younger than 18 in our people catalog, then we could + have implemented this check as follows:

+ +
+class person_pimpl: public person_pskel
+{
+public:
+  virtual void
+  age (short a)
+  {
+    if (a < 18)
+      _app_error (1);
+  }
+
+  ...
+};
+  
+ +

You can also set a system error by calling the _sys_error() + function inside a parser callback. This function has one argument of type + xml_schema::sys_error which was presented above. For + example:

+ +
+class person_pimpl: public person_pskel
+{
+public:
+  virtual void
+  pre ()
+  {
+    p_ = new person ();
+
+    if (p_ == 0)
+      _sys_error (xml_schema::sys_error::no_memory);
+  }
+
+  ...
+
+private:
+  person* p_;
+};
+  
+ + +

7.4 Reusing Parsers after an Error

+ +

After a successful execution a parser returns into the initial + state and can be used to parse another document without any + extra actions. On the other hand, if an error occurred during + parsing and you would like to reuse the parser to parse another + document, you need to explicitly reset it into the initial + state as shown in the following code fragment:

+ +
+int
+main ()
+{
+  ...
+
+  std::vector<std::string> files = ...
+
+  xml_schema::document_pimpl doc_p (people_p, "people");
+
+  for (size_t i = 0; i < files.size (); ++i)
+  {
+    try
+    {
+      people_p.pre ();
+      doc_p.parse (files[i]);
+      people_p.post_people ();
+    }
+    catch (const xml_schema::parser_exception&)
+    {
+      doc_p.reset ();
+    }
+  }
+}
+  
+ +

If you do not need to reuse parsers after an error for example + because your application terminates or you create a new parser + instance in such situations, then you can avoid generating + parser reset code by specifying the --suppress-reset + XSD/e compiler option.

+ +

Your individual parser implementations may also require extra + actions in order to bring them into a usable state after an + error. To accomplish this you can override the _reset() + virtual function as shown below. Notice that when you override the + _reset() function in your implementation, you should + always call the base skeleton version to allow it to reset + its state:

+ +
+class person_pimpl: public person_pskel
+{
+public:
+  virtual void
+  pre ()
+  {
+    p_ = new person ();
+  }
+
+  virtual void
+  _reset ()
+  {
+    person_pskel::_reset ();
+    delete p_;
+    p_ = 0;
+  }
+
+  ...
+
+private:
+  person* p_;
+};
+  
+ +

Note also that the _reset() mechanism is used only when + an error has occurred. To make sure that your parser implementations + arrive at the initial state during successful execution, use the + initialization (pre() and _pre()) and + finalization (post_*() and _post()) + callbacks.

+ + + + +

Appendix A — Supported XML Schema Constructs

+ +

The Embedded C++/Parser mapping supports validation of the following + W3C XML Schema constructs in the generated code.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstructNotes
Structure
element
attribute
any
anyAttribute
all
sequence
choice
complex type, empty content
complex type, mixed content
complex type, simple content extension
complex type, simple content restriction
complex type, complex content extension
complex type, complex content restriction
list
Facets
lengthString-based types.
minLengthString-based types.
maxLengthString-based types.
patternString-based types.
whiteSpaceString-based types.
enumerationString-based types.
minExclusiveInteger and floating-point types.
minInclusiveInteger and floating-point types.
maxExclusiveInteger and floating-point types.
maxInclusiveInteger and floating-point types.
Datatypes
byte
unsignedByte
short
unsignedShort
int
unsignedInt
long
unsignedLong
integer
nonPositiveInteger
nonNegativeInteger
positiveInteger
negativeInteger
boolean
float
double
decimal
string
normalizedString
token
Name
NMTOKEN
NCName
language
anyURI
IDIdentity constraint is not enforced.
IDREFIdentity constraint is not enforced.
NMTOKENS
IDREFSIdentity constraint is not enforced.
QName
base64Binary
hexBinary
date
dateTime
duration
gDay
gMonth
gMonthDay
gYear
gYearMonth
time
+ +
+
+ + + + diff --git a/doc/cxx/parser/guide/makefile b/doc/cxx/parser/guide/makefile new file mode 100644 index 0000000..48c37d9 --- /dev/null +++ b/doc/cxx/parser/guide/makefile @@ -0,0 +1,48 @@ +# file : doc/cxx/parser/guide/makefile +# author : Boris Kolpackov +# copyright : Copyright (c) 2006-2011 Code Synthesis Tools CC +# license : GNU GPL v2 + exceptions; see accompanying LICENSE file + +include $(dir $(lastword $(MAKEFILE_LIST)))../../../../build/bootstrap.make + +default := $(out_base)/ +dist := $(out_base)/.dist +dist-win := $(out_base)/.dist-win +cleandoc := $(out_base)/.cleandoc + +# Build. +# +$(default): $(out_base)/cxx-parser-e-guide.ps \ + $(out_base)/cxx-parser-e-guide.pdf + + +$(out_base)/cxx-parser-e-guide.ps: $(src_base)/index.xhtml \ + $(src_base)/figure-1.png \ + $(src_base)/guide.html2ps \ + | $(out_base)/. + $(call message,html2ps $<,html2ps -f $(src_base)/guide.html2ps -o $@ $<) + +$(out_base)/cxx-parser-e-guide.pdf: $(out_base)/cxx-parser-e-guide.ps | $(out_base)/. + $(call message,ps2pdf $<,ps2pdf14 $< $@) + +# Dist. +# +$(dist): path := $(subst $(src_root)/,,$(src_base)) +$(dist): $(out_base)/cxx-parser-e-guide.ps $(out_base)/cxx-parser-e-guide.pdf + $(call install-data,$(src_base)/figure-1.png,$(dist_prefix)/$(path)/figure-1.png) + $(call install-data,$(src_base)/index.xhtml,$(dist_prefix)/$(path)/index.xhtml) + $(call install-data,$(out_base)/cxx-parser-e-guide.ps,$(dist_prefix)/$(path)/cxx-parser-e-guide.ps) + $(call install-data,$(out_base)/cxx-parser-e-guide.pdf,$(dist_prefix)/$(path)/cxx-parser-e-guide.pdf) + +$(dist-win): $(dist) + + +# Clean +# +$(cleandoc): + $(call message,rm $$1,rm -f $$1,$(out_base)/cxx-parser-e-guide.ps) + $(call message,rm $$1,rm -f $$1,$(out_base)/cxx-parser-e-guide.pdf) + +# How to. +# +$(call include,$(bld_root)/install.make) diff --git a/doc/cxx/serializer/guide/figure-1.png b/doc/cxx/serializer/guide/figure-1.png new file mode 100644 index 0000000..8700758 Binary files /dev/null and b/doc/cxx/serializer/guide/figure-1.png differ diff --git a/doc/cxx/serializer/guide/figure-1.svg b/doc/cxx/serializer/guide/figure-1.svg new file mode 100644 index 0000000..68790f9 --- /dev/null +++ b/doc/cxx/serializer/guide/figure-1.svg @@ -0,0 +1,372 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + class people_simpl{ void person ();}; + + + class person_simpl{ void pre (); string first_name (); string last_name (); void gender (); short age ();}; + + + class string_simpl{ void pre (string);}; + + + class short_simpl{ void pre (short);}; + + + class gender_simpl{ void pre ();}; + + + + + + + diff --git a/doc/cxx/serializer/guide/guide.html2ps b/doc/cxx/serializer/guide/guide.html2ps new file mode 100644 index 0000000..9e5fc78 --- /dev/null +++ b/doc/cxx/serializer/guide/guide.html2ps @@ -0,0 +1,65 @@ +@html2ps { + option { + toc: hb; + colour: 1; + hyphenate: 1; + titlepage: 1; + } + + datefmt: "%B %Y"; + + titlepage { + content: " +
+

Embedded C++/Serializer Mapping

+

Getting Started Guide

+

 

+

 

+

 

+

 

+

 

+

 

+
+

Copyright © 2005-2011 CODE SYNTHESIS TOOLS CC

+ +

Permission is granted to copy, distribute and/or modify this + document under the terms of the + GNU Free + Documentation License, version 1.2; with no Invariant Sections, + no Front-Cover Texts and no Back-Cover Texts. +

+ +

This document is available in the following formats: + XHTML, + PDF, and + PostScript.

"; + } + + toc { + indent: 2em; + } + + header { + odd-right: $H; + even-left: $H; + } + + footer { + odd-left: $D; + odd-center: $T; + odd-right: $N; + + even-left: $N; + even-center: $T; + even-right: $D; + } +} + +body { + font-size: 12pt; + text-align: justify; +} + +pre { + font-size: 10pt; +} diff --git a/doc/cxx/serializer/guide/index.xhtml b/doc/cxx/serializer/guide/index.xhtml new file mode 100644 index 0000000..34ddbe1 --- /dev/null +++ b/doc/cxx/serializer/guide/index.xhtml @@ -0,0 +1,6542 @@ + + + + + + Embedded C++/Serializer Mapping Getting Started Guide + + + + + + + + + + + + + +
+
+ +
+ +
+
Embedded C++/Serializer Mapping
+
Getting Started Guide
+ +

Copyright © 2005-2011 CODE SYNTHESIS TOOLS CC

+ +

Permission is granted to copy, distribute and/or modify this + document under the terms of the + GNU Free + Documentation License, version 1.2; with no Invariant Sections, + no Front-Cover Texts and no Back-Cover Texts. +

+ +

This document is available in the following formats: + XHTML, + PDF, and + PostScript.

+ +
+ +

Table of Contents

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Preface + + + +
About This Document
More Information
+
1Introduction + + + +
1.1Mapping Overview
1.2Benefits
+
2Hello World Example + + + + + +
2.1Writing Schema
2.2Translating Schema to C++
2.3Implementing Application Logic
2.4Compiling and Running
+
3Serializer Skeletons + + + + + +
3.1Implementing the Gender Serializer
3.2Implementing the Person Serializer
3.3Implementing the People Serializer
3.4Connecting the Serializers Together
+
4Type Maps + + + + +
4.1Object Model
4.2Type Map File Format
4.3Serializer Implementations
+
5Serializer Callbacks + + + + + + +
5.1Optional Callback
5.2Sequence Callback
5.3Choice Callback
5.4Element Wildcard Callbacks
5.5Attribute Wildcard Callbacks
+
6Mapping Configuration + + + + + + + + + + +
6.1Standard Template Library
6.2Input/Output Stream Library
6.3C++ Exceptions
6.4XML Schema Validation
6.564-bit Integer Type
6.6Serializer Reuse
6.7Support for Polymorphism
6.8Custom Allocators
6.9A Minimal Example
+
7Built-In XML Schema Type Serializers + + + + + + + + + + + + + + + + +
7.1Floating-Point Type Serializers
7.2String-Based Type Serializers
7.3QName Serializer
7.4NMTOKENS and IDREFS Serializers
7.5base64Binary and hexBinary Serializers
7.6Time Zone Representation
7.7date Serializer
7.8dateTime Serializer
7.9duration Serializer
7.10gDay Serializer
7.11gMonth Serializer
7.12gMonthDay Serializer
7.13gYear Serializer
7.14gYearMonth Serializer
7.15time Serializer
+
8Document Serializer and Error Handling + + + + + +
8.1Document Serializer
8.2Exceptions
8.3Error Codes
8.4Reusing Serializers after an Error
+
Appendix A — Supported XML Schema Constructs
+
+ +

Preface

+ +

About This Document

+ +

The goal of this document is to provide you with an + understanding of the C++/Serializer programming model and allow you + to efficiently evaluate XSD/e against your project's technical + requirements. As such, this document is intended for embedded + C++ developers and software architects who are looking for an + embedded XML processing solution. Prior experience with XML + and C++ is required to understand this document. Basic + understanding of XML Schema is advantageous but not expected + or required. +

+ + +

More Information

+ +

Beyond this guide, you may also find the following sources of + information useful:

+ +
    +
  • XSD/e + Compiler Command Line Manual
  • + +
  • The INSTALL file in the XSD/e distribution provides + build instructions for various platforms.
  • + +
  • The examples/cxx/serializer/ directory in the XSD/e + distribution contains a collection of examples and a README + file with an overview of each example.
  • + +
  • The xsde-users + mailing list is the place to ask technical questions about XSD/e and the + Embedded C++/Serializer mapping. Furthermore, the + archives + may already have answers to some of your questions.
  • + +
+ + + +

1 Introduction

+ +

Welcome to CodeSynthesis XSD/e and the Embedded C++/Serializer mapping. + XSD/e is a dependency-free W3C XML Schema to C++ compiler for mobile, + embedded, and light-weight applications. Embedded C++/Serializer is an + XML Schema to C++ mapping that represents an XML vocabulary as a set of + serializer skeletons which you can implement to perform XML serialization + as required by your application logic. +

+ +

1.1 Mapping Overview

+ +

The Embedded C++/Serializer mapping provides event-driven, + stream-oriented XML serialization, XML Schema validation, + and C++ data binding. It was specifically designed and + optimized for mobile and embedded systems where hardware + constraints require high efficiency and economical use of + resources. As a result, the generated serializers are 2-10 + times faster than general-purpose validating XML serializers + while at the same time maintaining extremely low static and + dynamic memory footprints. For example, a validating serializer + executable can be as small as 60KB in size. The size can be + further reduced by disabling support for XML Schema validation. +

+ +

The generated code and the runtime library are also highly-portable + and, in their minimal configuration, can be used without STL, RTTI, + iostream, C++ exceptions, and C++ templates.

+ +

To speed up application development, the C++/Serializer mapping + can be instructed to generate sample serializer implementations + and a test driver which can then be filled with the application + logic code. The mapping also provides a wide range of + mechanisms for controlling and customizing the generated code.

+ +

The next chapter shows how to create a simple application + that uses the Embedded C++/Serializer mapping to validate + and serialize simple data to an XML document. The following + chapters describe the Embedded C++/Serializer mapping in more + detail.

+ +

1.2 Benefits

+ +

Traditional XML serialization APIs such as Document Object Model (DOM) + or XML Writer as well as general-purpose XML Schema validators have + a number of drawbacks that make them less suitable for creating + mobile and embedded XML processing applications. These drawbacks + include: +

+ +
    +
  • Text-based representation results in inefficient use of + resources.
  • + +
  • Extra validation code that is not used by the application.
  • + +
  • Generic representation of XML in terms of elements, attributes, + and text forces an application developer to write a substantial + amount of bridging code that identifies and transforms pieces + of information produced by the application logic to the text + encoding used in XML.
  • + +
  • Resulting applications are hard to debug, change, and + maintain.
  • +
+ +

In contrast, statically-typed, vocabulary-specific serializer + skeletons produced by the Embedded C++/Serializer mapping use + native data types (for example, integers are passed as + integers, not as text) and include validation code only for + XML Schema constructs that are used in the application. This + results in efficient use of resources and compact object code.

+ +

Furthermore, the serializer skeletons allow you to operate in your + domain terms instead of the generic elements, attributes, and + text. Automatic code generation frees you for more + interesting tasks (such as doing something useful with the + information that needs to be stored in XML) and + minimizes the effort needed to adapt your applications to changes + in the document structure. To summarize, the C++/Serializer mapping + has the following key advantages over generic XML serialization APIs:

+ +
    +
  • Ease of use. The generated code hides all the complexity + associated with recreating the document structure, maintaining the + state, and converting the data from types suitable for + manipulation by the application logic to the text representation + used in XML.
  • + +
  • Natural representation. The generated serializer skeletons + implement serializer callbacks as virtual functions with names + corresponding to elements and attributes in XML. As a result, + you serialize the data using your domain vocabulary instead + of generic elements, attributes, and text. +
  • + +
  • Concise code. With a separate serializer skeleton for each + XML Schema type, the application implementation is simpler + and thus easier to read and understand.
  • + +
  • Safety. The data is passed by serializer callbacks as + statically typed objects. The serializer callbacks themselves + are virtual functions. This helps catch programming errors + at compile-time rather than at runtime.
  • + +
  • Maintainability. Automatic code generation minimizes the + effort needed to adapt the application to changes in the + document structure. With static typing, the C++ compiler + can pin-point the places in the application code that need to be + changed.
  • + +
  • Efficiency. The generated serializer skeletons use native + data types and combine validation and data-to-text + conversion in a single step. This makes them much more efficient + than traditional architectures with separate stages for validation + and data conversion.
  • +
+ + + + + +

2 Hello World Example

+ +

In this chapter we will examine how to create a very simple XML + document using the XSD/e-generated C++/Serializer skeletons. + + All the code presented in this chapter is based on the hello + example which can be found in the examples/cxx/serializer/ + directory of the XSD/e distribution.

+ +

2.1 Writing Schema

+ +

First, we need to get an idea about the structure of the XML + document that we are going to create. The sample XML that + we will try to produce with our Hello application looks like + this:

+ +
+<hello>
+
+  <greeting>Hello</greeting>
+
+  <name>sun</name>
+  <name>moon</name>
+  <name>world</name>
+
+</hello>
+      
+ +

Then we can write a description of the above XML in the + XML Schema language and save it into hello.xsd:

+ +
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="hello">
+    <xs:sequence>
+      <xs:element name="greeting" type="xs:string"/>
+      <xs:element name="name" type="xs:string" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="hello" type="hello"/>
+
+</xs:schema>
+      
+ +

Even if you are not familiar with the XML Schema language, it + should be easy to connect declarations in hello.xsd + to elements in the sample XML document above. The hello + type is defined as a sequence of the nested greeting + and name elements. Note that the term sequence in XML + Schema means that elements should appear in a particular order + as opposed to appearing multiple times. The name + element has its maxOccurs property set to + unbounded which means it can appear multiple times + in an XML document. Finally, the globally-defined hello + element prescribes the root element for our vocabulary. For an + easily-approachable introduction to XML Schema refer to + XML Schema Part 0: + Primer.

+ +

The above schema is a specification of our vocabulary; it tells + everybody what valid XML instances of our vocabulary should look + like. The next step is to compile this schema to generate C++ + serializer skeletons.

+ +

2.2 Translating Schema to C++

+ +

Now we are ready to translate our hello.xsd to C++ + serializer skeletons. To do this we invoke the XSD/e compiler + from a terminal (UNIX) or a command prompt (Windows): +

+ +
+$ xsde cxx-serializer hello.xsd
+  
+ +

The XSD/e compiler produces two C++ files: hello-sskel.hxx + and hello-sskel.cxx. The following code fragment is taken + from hello-sskel.hxx; it should give you an idea about what + gets generated: +

+ +
+class hello_sskel
+{
+public:
+  // Serializer callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual std::string
+  greeting () = 0;
+
+  virtual bool
+  name_next () = 0;
+
+  virtual std::string
+  name () = 0;
+
+  virtual void
+  post ();
+
+  // Serializer construction API.
+  //
+  void
+  greeting_serializer (xml_schema::string_sskel&);
+
+  void
+  name_serializer (xml_schema::string_sskel&);
+
+  void
+  serializers (xml_schema::string_sskel& /* greeting */,
+               xml_schema::string_sskel& /* name */);
+
+private:
+  ...
+};
+  
+ +

The first five member functions shown above are called serializer + callbacks. You would normally override them in your implementation + of the serializer. Let's go through all of them one by one.

+ +

The pre() function is an initialization callback. It is + called when a new element of type hello is about + to be serialized. You would normally use this function to initialize + data structures, such as iterators, which will be used during + serialization. As we will see in subsequent chapters, there is + also a way to pass an argument to this function which may be + useful if you are serializing an in-memory data structure + to XML. The default implementation of the initialization callback + does nothing.

+ +

The post() function is a finalization callback. It is + called when serialization of the element is completed. If necessary, + you can use this function to perform cleanups of data structures + initialized in pre() or during serialization. + The default implementation of the finalization callback also does + nothing. +

+ +

The greeting() and name() functions are + called when the greeting and name elements + are about to be serialized and the values for these elements need + to be provided. Because the name element can be + repeated several times (note the maxOccurs="unbounded" + attribute in the schema), the serializer skeleton also has the + name_next() function which is called before + name() to check if another name element + needs to be serialized.

+ +

The last three functions are for connecting serializers to each other. + For example, there is a predefined serializer for built-in XML Schema + type string in the XSD/e runtime. We will be using it to + serialize the values of greeting and name + elements, as shown in the next section.

+ +

2.3 Implementing Application Logic

+ +

At this point we have all the parts we need to create our + sample XML document. The first step is to implement the + serializer: +

+ +
+#include <string>
+#include <vector>
+#include "hello-sskel.hxx"
+
+struct hello_simpl: hello_sskel
+{
+  hello_simpl ()
+  {
+    names_.push_back ("sun");
+    names_.push_back ("moon");
+    names_.push_back ("world");
+  }
+
+  virtual void
+  pre ()
+  {
+    i_ = names_.begin ();
+  }
+
+  virtual std::string
+  greeting ()
+  {
+    return "Hello";
+  }
+
+  virtual bool
+  name_next ()
+  {
+    return i_ != names_.end ();
+  }
+
+  virtual std::string
+  name ()
+  {
+    return *i_++;
+  }
+
+private:
+  typedef std::vector<std::string> names;
+
+  names names_;
+  names::iterator i_;
+};
+  
+ +

We use the hello_simpl's constructor to initialize + a vector of names. Then, in the pre() initialization + callback, we initialize an iterator to point to the beginning of the + names vector. The greeting() callback + simply returns the string representing our greeting. The + name_next() callback checks if we reached the + end of the names vector and returns false + if that's the case. The name() callback returns + the next name from the names vector and advances the iterator. + Note that name() is not called if name_next() + returned false. Finally, we left post() with the + default implementations since we don't have anything to cleanup.

+ +

Now it is time to put this serializer implementation to work:

+ +
+#include <iostream>
+
+using namespace std;
+
+int
+main ()
+{
+  try
+  {
+    // Construct the serializer.
+    //
+    xml_schema::string_simpl string_s;
+    hello_simpl hello_s;
+
+    hello_s.greeting_serializer (string_s);
+    hello_s.name_serializer (string_s);
+
+    // Create the XML document.
+    //
+    xml_schema::document_simpl doc_s (hello_s, "hello");
+
+    hello_s.pre ();
+    doc_s.serialize (cout, xml_schema::document_simpl::pretty_print);
+    hello_s.post ();
+  }
+  catch (const xml_schema::serializer_exception& e)
+  {
+    cerr << "error: " << e.text () << endl;
+    return 1;
+  }
+}
+  
+ +

The first part of this code snippet instantiates individual serializers + and assembles them into a complete vocabulary serializer. + xml_schema::string_simpl is an implementation of a + serializer for built-in XML Schema type string. It is + provided by the XSD/e runtime along with serializers for other built-in + types (for more information on the built-in serializers see + Chapter 7, "Built-In XML Schema Type Serializers"). + We use string_simpl to serialize the greeting + and name elements as indicated by the calls to + greeting_serializer() and name_serializer(). +

+ +

Then we instantiate a document serializer (doc_s). The + first argument to its constructor is the serializer for the root + element (hello_s in our case). The second argument is + the root element name. +

+ +

The final piece is the calls to pre(), + serialize(), and post(). The call to + serialize() performs the actual XML serialization + with the result written to std::cout. The second + argument in this call is a flag that requests pretty-printing + of the resulting XML document. You would normally specify this flag + during testing to obtain easily-readable XML and remove it + in production to get faster serialization and smaller documents. + The calls to pre() and + post() make sure that the serializer for the + root element can perform proper initialization and cleanup.

+ +

While our serializer implementation and test driver are pretty small and + easy to write by hand, for bigger XML vocabularies it can be a + substantial effort. To help with this task XSD/e can automatically + generate sample serializer implementations and a test driver from your + schemas. To request the generation of a sample implementation with + empty function bodies specify the --generate-empty-impl + option. To request the generation of a test driver you can use the + --generate-test-driver option. For more information + on these options refer to the + XSD/e + Compiler Command Line Manual.

+ +

2.4 Compiling and Running

+ +

After saving all the parts from the previous section in + driver.cxx, we are ready to compile and run + our first application. On UNIX this can be done with the + following commands: +

+ +
+$ c++ -I.../libxsde -c driver.cxx hello-sskel.cxx
+$ c++ -o driver driver.o hello-sskel.o .../libxsde/xsde/libxsde.a
+$ ./driver
+<hello>
+  <greeting>Hello</greeting>
+  <name>sun</name>
+  <name>moon</name>
+  <name>world</name>
+</hello>
+  
+ +

Here .../libxsde represents the path to the + libxsde directory in the XSD/e distribution.

+ +

+ We can also test XML Schema validation. We can "forget" to + add any names to the vector so that name_next() + returns false on the first call:

+ +
+struct hello_simpl: hello_sskel
+{
+  hello_simpl ()
+  {
+    /*
+    names_.push_back ("sun");
+    names_.push_back ("moon");
+    names_.push_back ("world");
+    */
+  }
+  ...
+};
+  
+ +

This will violate our vocabulary specification which requires + at least one name element to be present. If we + make the above change and recompile our application, we will + get the following output:

+ +
+$ ./driver
+error: expected element not encountered
+  
+ + + + + +

3 Serializer Skeletons

+ +

As we have seen in the previous chapter, the XSD/e compiler generates + a serializer skeleton class for each type defined in XML Schema. In + this chapter we will take a closer look at different functions + that comprise a serializer skeleton as well as the way to connect + our implementations of these serializer skeletons to create a complete + vocabulary serializer.

+ +

In this and subsequent chapters we will use the following + schema that describes a collection of person records. We + save it in people.xsd:

+ +
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:simpleType name="gender">
+    <xs:restriction base="xs:string">
+      <xs:enumeration value="male"/>
+      <xs:enumeration value="female"/>
+    </xs:restriction>
+  </xs:simpleType>
+
+  <xs:complexType name="person">
+    <xs:sequence>
+      <xs:element name="first-name" type="xs:string"/>
+      <xs:element name="last-name" type="xs:string"/>
+      <xs:element name="gender" type="gender"/>
+      <xs:element name="age" type="xs:short"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:complexType name="people">
+    <xs:sequence>
+      <xs:element name="person" type="person" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="people" type="people"/>
+
+</xs:schema>
+  
+ +

A sample XML instance to go along with this schema could look like + this:

+ +
+<people>
+  <person>
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+  <person>
+    <first-name>Jane</first-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+</people>
+  
+ +

Compiling people.xsd with the XSD/e compiler results + in three serializer skeletons being generated: gender_sskel, + person_sskel, and people_sskel. We are going + to examine and implement each of them in the subsequent sections.

+ +

In the previous chapter we used pre-initialized, static data to + create an XML document. In this chapter we will use the standard + input (std::cin) as the source of data. This approach + reflects a common design theme where the data to be serialized is + computed on the fly instead of being stored in, for example, an + in-memory object model. The next chapter will examine mechanisms + provided by the C++/Serializer mapping for serializing in-memory + object models.

+ +

3.1 Implementing the Gender Serializer

+ +

The generated gender_sskel serializer skeleton looks + like this:

+ +
+class gender_sskel: public xml_schema::string_sskel
+{
+public:
+  gender_sskel (xml_schema::string_sskel* base_impl)
+
+  // Serializer callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual void
+  post ();
+};
+  
+ +

Notice that gender_sskel inherits from + xml_schema::string_sskel which is a serializer + skeleton for built-in XML Schema type string + and is predefined in the XSD/e runtime library. This is an example + of the general rule that serializer skeletons follow: if a type + in XML Schema inherits from another then there will be an + equivalent inheritance between the corresponding serializer + skeleton classes. The gender_sskel class also + declares a constructor which expects a pointer to the base + serializer skeleton. We will discuss the purpose of this + constructor shortly.

+ +

The pre() and post() callbacks should look + familiar from the previous chapter. Let's now implement this + serializer. Our implementation will simply query the gender + value from the standard input stream (std::cin):

+ + +
+#include <string>
+#include <iostream>
+
+using namespace std;
+
+class gender_simpl: public gender_sskel
+{
+public:
+  gender_simpl ()
+    : gender_sskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  pre ()
+  {
+    string g;
+    cerr << "gender (male/female): ";
+    getline (cin, g);
+    base_impl_.pre (g);
+  }
+
+private:
+  xml_schema::string_simpl base_impl_;
+};
+  
+ +

While the code is quite short, there is a lot going on. First, + notice that we define a member variable base_impl_ + of type xml_schema::string_simpl and then pass + it to the gender_sskel's constructor. We have + encountered xml_schema::string_simpl already; it is an + implementation of the xml_schema::string_sskel serializer + skeleton for built-in XML Schema type string. By + passing base_impl_ to the gender_sskel's + constructor we provide an implementation for the part of the + serializer skeleton that is inherited from string_sskel.

+ +

This is another common theme in the C++/Serializer programming model: + reusing implementations of the base serializers in the derived ones. + In our case, string_simpl will do all the dirty work of + serializing the data which we pass to it with the call to + base_impl_.pre(). For more information on serializer + implementation reuse refer to Section 6.6, + "Serializer Reuse".

+ +

In case you are curious, here are the definitions for + xml_schema::string_sskel and + xml_schema::string_simpl:

+ +
+namespace xml_schema
+{
+  class string_sskel: public serializer_simple_content
+  {
+  public:
+    virtual void
+    pre (const std::string&) = 0;
+  };
+
+  class string_simpl: public string_sskel
+  {
+  public:
+    virtual void
+    pre (const std::string&);
+
+    virtual void
+    _serialize_content ();
+
+  protected:
+    std::string value_;
+  };
+}
+  
+ +

There are two new pieces in this code that we haven't seen yet. + Those are the xml_schema::serializer_simple_content + class and the _serialize_content() function. + The serializer_simple_content class is defined in + the XSD/e runtime and is a base class for all serializer skeletons + that conform to the simple content model in XML Schema. Types with + the simple content model cannot have nested elements—only + text and attributes. There is also the + xml_schema::serializer_complex_content class which + corresponds to the complex content mode (types with nested elements, + for example, person from people.xsd).

+ +

The _serialize_content() function is a low-level + serializer callback that is called to perform actual content + serialization (that is to output text or nested elements). There + is also the _serialize_attributes() callback which + is called to serialize attributes in complex types. You will seldom + need to use these callbacks directly. Using implementations for the + built-in serializers provided by the XSD/e runtime is usually a + simpler and more convenient alternative.

+ +

Another bit of information that is useful to know about is + the _pre() and _post() serialization + callbacks. Remember we talked about the pre() and + post() callbacks in the previous chapter? The + _pre() and _post have very + similar but somewhat different roles. As a result, each + serializer skeleton has four special callbacks:

+ +
+  virtual void
+  pre ();
+
+  virtual void
+  _pre ();
+
+  virtual void
+  _post ();
+
+  virtual void
+  post ();
+  
+ +

pre() and _pre() are initialization + callbacks. They get called in that order before a new instance of the type + is about to be serialized. The difference between pre() and + _pre() is conventional: pre() can + be completely overridden by a derived serializer. The derived + serializer can also override _pre() but has to always call + the original version. This allows you to partition initialization + into customizable and required parts.

+ +

Similarly, _post() and post() are + finalization callbacks with exactly the same semantics: + post() can be completely overridden by the derived + serializer while the original _post() should always be + called. +

+ +

At this point you might be wondering why some pre() + callbacks, for example string_sskel::pre(), have an + argument with which they receive the data they need to serialize while + others, for example gender_sskel::pre(), have no such + argument. This is a valid concern and it will be addressed in the + next chapter.

+ +

3.2 Implementing the Person Serializer

+ +

The generated person_sskel serializer skeleton looks like + this:

+ +
+class person_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  // Serializer callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual std::string
+  first_name () = 0;
+
+  virtual std::string
+  last_name () = 0;
+
+  virtual void
+  gender ();
+
+  virtual short
+  age () = 0;
+
+  virtual void
+  post ();
+
+  // Serializer construction API.
+  //
+  void
+  first_name_serializer (xml_schema::string_sskel&);
+
+  void
+  last_name_serializer (xml_schema::string_sskel&);
+
+  void
+  gender_serializer (gender_sskel&);
+
+  void
+  age_serializer (xml_schema::short_sskel&);
+
+  void
+  serializers (xml_schema::string_sskel& /* first-name */,
+               xml_schema::string_sskel& /* last-name */,
+               gender_sskel&             /* gender */,
+               xml_schema::short_sskel&  /* age */);
+};
+  
+ + +

As you can see, we have a serializer callback for each of the nested + elements found in the person XML Schema type. + The implementation of this serializer is straightforward:

+ +
+class person_simpl: public person_sskel
+{
+public:
+  virtual string
+  first_name ()
+  {
+    string fn;
+    cerr << "first name: ";
+    getline (cin, fn);
+    return fn;
+  }
+
+  virtual std::string
+  last_name ()
+  {
+    string ln;
+    cerr << "last name: ";
+    getline (cin, ln);
+    return ln;
+  }
+
+  virtual short
+  age ()
+  {
+    short a;
+    cerr << "age: ";
+    cin >> a;
+    return a;
+  }
+};
+  
+ +

Notice that we didn't need to override the gender() + callback because all the work is done by gender_simpl.

+ +

3.3 Implementing the People Serializer

+ +

The generated people_sskel serializer skeleton looks like + this:

+ +
+class people_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  // Serializer callbacks. Override them in your implementation.
+  //
+  virtual void
+  pre ();
+
+  virtual bool
+  person_next () = 0;
+
+  virtual void
+  person ();
+
+  virtual void
+  post ();
+
+  // Serializer construction API.
+  //
+  void
+  person_serializer (person_sskel&);
+
+  void
+  serializers (person_sskel& /* person */);
+};
+  
+ +

The person_next() callback will be called before serializing + each person element. Our implementation of + person_next() asks the user whether to serialize + another person record:

+ +
+class people_simpl: public people_sskel
+{
+public:
+  virtual bool
+  person_next ()
+  {
+    string s;
+    cerr << "serialize another person record (y/n): ";
+    cin >> ws; // Skip leading whitespaces.
+    getline (cin, s);
+    return s == "y";
+  }
+};
+  
+ +

Now it is time to put everything together.

+ + +

3.4 Connecting the Serializers Together

+ +

At this point we have all the individual serializers implemented + and can proceed to assemble them into a complete serializer + for our XML vocabulary. The first step is to instantiate + all the individual serializers that we will need:

+ +
+xml_schema::short_simpl short_s;
+xml_schema::string_simpl string_s;
+
+gender_simpl gender_s;
+person_simpl person_s;
+people_simpl people_s;
+  
+ +

Notice that our schema uses two built-in XML Schema types: + string for the first-name and + last-name elements as well as short + for age. We will use predefined serializers that + come with the XSD/e runtime to serialize these types. The next + step is to connect all the individual serializers. We do this + with the help of functions defined in the serializer + skeletons and marked with the "Serializer Construction API" + comment. One way to do it is to connect each individual + serializers by calling the *_serializer() functions:

+ +
+person_s.first_name_serializer (string_s);
+person_s.last_name_serializer (string_s);
+person_s.gender_serializer (gender_s);
+person_s.age_serializer (short_s);
+
+people_s.person_serializer (person_s);
+  
+ +

You might be wondering what happens if you do not provide + a serializer by not calling one of the *_serializer() + functions. In that case the corresponding XML fragment will be + skipped.

+ +

An alternative, shorter, way to connect the serializers is by using + the serializers() functions which connects all the + serializers for a given type at once:

+ +
+person_s.serializers (string_s, string_s, gender_s, short_s);
+people_s.serializers (person_s);
+  
+ +

The following figure illustrates the resulting connections. Notice + the correspondence between return types of element callbacks and + argument types of the pre() functions that are connected + by the arrows.

+ + +
+ +

The last step is the construction of the document serializer and + invocation of the complete serializer to produce an XML + document:

+ +
+xml_schema::document_simpl doc_s (people_s, "people");
+
+std::ostringstream os;
+
+people_s.pre ();
+doc_s.serialize (os, xml_schema::document_simpl::pretty_print);
+people_s.post ();
+
+cout << os.str ();
+  
+ +

Note that we first serialize the document into an + std::ostringstream object and then write + the result to the standard output stream. This is done + to prevent the input prompts and output XML from interleaving. + However, writing XML directly to std::cout in + this example is a great way to observe the moments in the XML + document construction process at which serializer callbacks are + being called.

+ +

Let's consider xml_schema::document_simpl in + more detail. While the exact definition of this class + varies depending on the mapping configuration, here is + the part relevant to our example:

+ +
+namespace xml_schema
+{
+  class document_simpl
+  {
+  public:
+    document_simpl (xml_schema::serializer_base&,
+                    const std::string& root_element_name);
+
+    document_simpl (xml_schema::serializer_base&,
+                    const std::string& root_element_namespace,
+                    const std::string& root_element_name);
+
+    typedef unsigned short flags;
+    static const flags pretty_print;
+
+    void
+    serialize (std::ostream&, flags = 0);
+  };
+}
+  
+ +

xml_schema::document_simpl is a root serializer for + the vocabulary. The first argument to its constructors is the + serializer for the type of the root element (people_simpl + in our case). Because a type serializer is only concerned with + the element's content and not with the element's name, we need + to specify the root element name somewhere. That's + what is passed as the second and third arguments to the + document_simpl's constructors.

+ +

There is also a number of overloaded serialize() + function defined in the document_simpl class. + At the moment we are only interested in the version that + writes XML to a standard output stream. For more information + on the xml_schema::document_simpl class + refer to Chapter 8, "Document Serializer and Error + Handling".

+ +

Let's now consider a step-by-step list of actions that happen + as we serialize the following sample XML document:

+ +
+<people>
+  <person>
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+</people>
+  
+ + +
    +
  1. people_s.pre() is called from + main(). We did not provide any implementation + for this callback so this call is a no-op.
  2. + +
  3. doc_s.serialize(os) is called from + main(). The document serializer + writes out the <people> opening tag + and calls _pre() on the root element + type serializer (people_s) which is + also a no-op. Serialization is delegated to + people_s.
  4. + +
  5. The people_s serializer calls person_next() + to determine if another person element + needs to be serialized. Our implementation ask the user + (who answers "y") and returns true.
  6. + +
  7. The people_s serializer calls person() + which is a no-op. It then calls pre() on + person_s (no-op), writes out the + <person> opening tag, and calls _pre() + on person_s (no-op). Serialization is delegated to + person_s.
  8. + +
  9. The person_s serializer calls first_name() + that returns a first name which it asks the user to enter. + person_s then calls pre() on + string_s and passes the name returned from + first_name() as its argument. It then writes + out the <first-name> opening tag and calls + _pre() on string_s. Serialization + is delegated to string_s.
  10. + +
  11. The _serialize_content() callback is called on + string_s which writes out the string passed + to it in the pre() call.
  12. + +
  13. Control is returned to person_s which + calls _post() on string_s, writes + out the </first-name> closing tag, and calls + post() on string_s.
  14. + +
  15. Steps analogous to 5-7 are performed for the last-name, + gender, and age elements.
  16. + +
  17. Control is returned to people_s + which calls _post() on person_s (no-op), + writes out the </person> closing tag, and calls + post() on person_s (no-op).
  18. + +
  19. The people_s serializer calls person_next() + to determine if another person element + needs to be serialized. Our implementation ask the user + (who answers "n") and returns false.
  20. + +
  21. Control is returned to doc_s which calls + _post() on people_s (no-op) and + writes out the </people> closing tag.
  22. + +
  23. Control is returned to main() which + calls post() on people_s (no-op).
  24. +
+ + + + + +

4 Type Maps

+ +

There are many useful things you can do inside serializer callbacks as they + are right now. There are, however, times when you want to propagate + some information from one serializer to another or from the caller of + the serializer. One common task that would greatly benefit from such a + possibility is serializing a tree-like in-memory object model to XML. + During execution, each individual serializer would be responsible + for disaggregating and serializing a specific portion of the tree + and delegating the rest to its sub-serializers.

+ +

In this chapter we will discuss the mechanisms offered by the + C++/Serializer mapping for passing information between individual + serializers and see how to use them to serialize a sample object + model for our people vocabulary.

+ +

4.1 Object Model

+ +

An object model for our person record example could + look like this (saved in the people.hxx file):

+ +
+#include <string>
+#include <vector>
+
+enum gender
+{
+  male,
+  female
+};
+
+class person
+{
+public:
+  person (const std::string& first,
+          const std::string& last,
+          ::gender gender,
+          short age)
+    : first_ (first), last_ (last),
+      gender_ (gender), age_ (age)
+  {
+  }
+
+  const std::string&
+  first () const
+  {
+    return first_;
+  }
+
+  const std::string&
+  last () const
+  {
+    return last_;
+  }
+
+  ::gender
+  gender () const
+  {
+    return gender_;
+  }
+
+  short
+  age () const
+  {
+    return age_;
+  }
+
+private:
+  std::string first_;
+  std::string last_;
+  ::gender gender_;
+  short age_;
+};
+
+typedef std::vector<person> people;
+  
+ +

While it is clear which serializer is responsible for which part of + the object model, it is not exactly clear how, for + example, person_simpl will pass gender + to gender_simpl. You might have noticed that + string_simpl manages to receive its value from the + first_name() callback. Let's + see how we can utilize the same mechanism to propagate our + own data.

+ +

There is a way to tell the XSD/e compiler that you want to + exchange data between serializers. More precisely, for each + type defined in XML Schema, you can tell the compiler two things. + First, the argument type of the pre() callback + in the serializer skeleton generated for this type. And, second, + the return type for callbacks corresponding to elements and + attributes of this type. For example, for XML Schema type + gender we can specify the argument type for + pre() in the gender_sskel + skeleton and the return type for the gender() callback + in the person_sskel skeleton. As you might have guessed, + the generated code will then pass the return value from an + element or attribute callback (person_sskel::gender() + in our case) to the pre() callback of the corresponding + serializer skeleton (gender_sskel::pre() in our case).

+ +

The way to tell the XSD/e compiler about these XML Schema to + C++ mappings is with type map files. Here is a simple type + map for the gender type from the previous paragraph.

+ +
+include "people.hxx";
+gender ::gender ::gender;
+  
+ +

The first line indicates that the generated code must include + people.hxx in order to get the definition for the + gender type. The second line specifies that both + argument and return types for the gender + XML Schema type should be the ::gender C++ enum + (we use fully-qualified C++ names to avoid name clashes). + The next section will describe the type map format in more detail. + We save this type map in people.map and + then translate our schemas with the --type-map + option to let the XSD/e compiler know about our type map:

+ +
+$ xsde cxx-serializer --type-map people.map people.xsd
+  
+ +

If we now look at the generated people-sskel.hxx, + we will see the following changes in the gender_sskel and + person_sskel skeletons:

+ +
+#include "people.hxx"
+
+class gender_sskel: public xml_schema::string_sskel
+{
+  virtual void
+  pre (::gender) = 0;
+
+  ...
+};
+
+class person_sskel: public xml_schema::serializer_complex_content
+{
+  virtual ::gender
+  gender () = 0;
+
+  ...
+};
+  
+ +

Notice that #include "people.hxx" was added to + the generated header file from the type map to provide the + definition for the gender enum.

+ +

4.2 Type Map File Format

+ +

Type map files are used to define a mapping between XML Schema + and C++ types. The compiler uses this information + to determine argument types of pre() + callbacks in serializer skeletons corresponding to XML Schema + types as well as return types for callbacks corresponding + to elements and attributes of these types.

+ +

The compiler has a set of predefined mapping rules that map + the built-in XML Schema types to suitable C++ types (discussed + below) and all other types to void. + By providing your own type maps you can override these predefined + rules. The format of the type map file is presented below: +

+ +
+namespace <schema-namespace> [<cxx-namespace>]
+{
+  (include <file-name>;)*
+  ([type] <schema-type> <cxx-ret-type> [<cxx-arg-type>];)*
+}
+  
+ +

Both <schema-namespace> and + <schema-type> are regex patterns while + <cxx-namespace>, + <cxx-ret-type>, and + <cxx-arg-type> are regex pattern + substitutions. All names can be optionally enclosed in + " ", for example, to include white-spaces.

+ +

<schema-namespace> determines XML + Schema namespace. Optional <cxx-namespace> + is prefixed to every C++ type name in this namespace declaration. + <cxx-ret-type> is a C++ type name that is + used as a return type for the element and attribute callbacks corresponding + to this schema type. Optional <cxx-arg-type> + is an argument type for the pre() callback in the serializer + skeleton for this schema type. If <cxx-arg-type> + is not specified, it defaults to <cxx-ret-type> + if <cxx-ret-type> ends with * or + & (that is, it is a pointer or a reference) and + const <cxx-ret-type>& + otherwise. + <file-name> is a file name either in the + " " or < > format + and is added with the #include directive to + the generated code.

+ +

The # character starts a comment that ends + with a new line or end of file. To specify a name that contains + # enclose it in " ". + For example:

+ +
+namespace http://www.example.com/xmlns/my my
+{
+  include "my.hxx";
+
+  # Pass apples by value.
+  #
+  apple apple;
+
+  # Pass oranges as pointers.
+  #
+  orange orange_t*;
+}
+  
+ +

In the example above, for the + http://www.example.com/xmlns/my#orange + XML Schema type, the my::orange_t* C++ type will + be used as both return and argument types.

+ +

Several namespace declarations can be specified in a single + file. The namespace declaration can also be completely + omitted to map types in a schema without a namespace. For + instance:

+ +
+include "my.hxx";
+apple apple;
+
+namespace http://www.example.com/xmlns/my
+{
+  orange "const orange_t*";
+}
+  
+ +

The compiler has a number of predefined mapping rules for + the built-in XML Schema types which can be presented as the + following map files:

+ +
+namespace http://www.w3.org/2001/XMLSchema
+{
+  boolean bool bool;
+
+  byte "signed char" "signed char";
+  unsignedByte "unsigned char" "unsigned char";
+
+  short short short;
+  unsignedShort "unsigned short" "unsigned short";
+
+  int int int;
+  unsignedInt "unsigned int" "unsigned int";
+
+  long "long long" "long long";
+  unsignedLong "unsigned long long" "unsigned long long";
+
+  integer long long;
+
+  negativeInteger long long;
+  nonPositiveInteger long long;
+
+  positiveInteger "unsigned long" "unsigned long";
+  nonNegativeInteger "unsigned long" "unsigned long";
+
+  float float float;
+  double double double;
+  decimal double double;
+
+  NMTOKENS "const xml_schema::string_sequence*";
+  IDREFS "const xml_schema::string_sequence*";
+
+  base64Binary "const xml_schema::buffer*";
+  hexBinary "const xml_schema::buffer*";
+
+  date xml_schema::date;
+  dateTime xml_schema::date_time;
+  duration xml_schema::duration;
+  gDay xml_schema::gday;
+  gMonth xml_schema::gmonth;
+  gMonthDay xml_schema::gmonth_day;
+  gYear xml_schema::gyear;
+  gYearMonth xml_schema::gyear_month;
+  time xml_schema::time;
+}
+  
+ +

If STL is enabled (Section 6.1, "Standard Template + Library"), the following mapping is used for the string-based + XML Schema built-in types:

+ +
+namespace http://www.w3.org/2001/XMLSchema
+{
+  include <string>;
+
+  anySimpleType std::string;
+
+  string std::string;
+  normalizedString std::string;
+  token std::string;
+  Name std::string;
+  NMTOKEN std::string;
+  NCName std::string;
+  ID std::string;
+  IDREF std::string;
+  language std::string;
+  anyURI std::string;
+
+  QName xml_schema::qname;
+}
+  
+ +

Otherwise, a C string-based mapping is used:

+ +
+namespace http://www.w3.org/2001/XMLSchema
+{
+  anySimpleType "const char*";
+
+  string "const char*";
+  normalizedString "const char*";
+  token "const char*";
+  Name "const char*";
+  NMTOKEN "const char*";
+  NCName "const char*";
+  ID "const char*";
+  IDREF "const char*";
+  language "const char*";
+  anyURI "const char*";
+
+  QName "const xml_schema::qname*";
+}
+  
+ +

For more information about the mapping of the built-in XML Schema types + to C++ types refer to Chapter 7, "Built-In XML Schema Type + Serializers". The last predefined rule maps anything that wasn't + mapped by previous rules to void:

+ +
+namespace .*
+{
+  .* void void;
+}
+  
+ + +

When you provide your own type maps with the + --type-map option, they are evaluated first. This + allows you to selectively override any + of the predefined rules. Note also that if you change the mapping + of a built-in XML Schema type then it becomes your responsibility + to provide the corresponding serializer skeleton and implementation + in the xml_schema namespace. You can include the + custom definitions into the generated header file using the + --hxx-prologue-* options.

+ +

4.3 Serializer Implementations

+ +

With the knowledge from the previous section, we can proceed + with creating a type map that maps types in the people.xsd + schema to our object model classes in + people.hxx. In fact, we already have the beginning + of our type map file in people.map. Let's extend + it with the rest of the types:

+ +
+include "people.hxx";
+
+gender ::gender ::gender;
+person "const ::person&";
+people "const ::people&";
+  
+ +

A few things to note about this type map. We decided to pass + the person and people objects by + constant references in order to avoid unnecessary copying. + We can do this because we know that our object model is + present for the duration of serialization. We also did not + provide any mappings for built-in XML Schema types + string and short because they + are handled by the predefined rules and we are happy with + the result. Note also that all C++ types are fully qualified. + This is done to avoid potential name conflicts in the generated + code. Now we can recompile our schema and move on to implementing + the serializers:

+ +
+$ xsde cxx-serializer --type-map people.map people.xsd
+  
+ +

Here is the implementation of our three serializers in full. One + way to save typing when implementing your own serializers is + to open the generated code and copy the signatures of serializer + callbacks into your code. Or you could always auto generate the + sample implementations and fill them with your code.

+ +
+#include "people-sskel.hxx"
+
+const char* gender_strings[] = {"male", "female"};
+
+class gender_simpl: public gender_sskel
+{
+public:
+  gender_simpl ()
+    : gender_sskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  pre (gender g)
+  {
+    base_impl_.pre (gender_strings[g]);
+  }
+
+private:
+  xml_schema::string_simpl base_impl_;
+};
+
+class person_simpl: public person_sskel
+{
+public:
+  virtual void
+  pre (const person& p)
+  {
+    p_ = &p;
+  }
+
+  virtual std::string
+  first_name ()
+  {
+    return p_->first ();
+  }
+
+  virtual std::string
+  last_name ()
+  {
+    return p_->last ();
+  }
+
+  virtual ::gender
+  gender ()
+  {
+    return p_->gender ();
+  }
+
+  virtual short
+  age ()
+  {
+    return p_->age ();
+  }
+
+private:
+  const person* p_;
+};
+
+class people_simpl: public people_sskel
+{
+public:
+  virtual void
+  pre (const people& p)
+  {
+    p_ = &p;
+    i_ = p_->begin ();
+  }
+
+  virtual bool
+  person_next ()
+  {
+    return i_ != p_->end ();
+  }
+
+  virtual const ::person&
+  person ()
+  {
+    return *i_++;
+  }
+
+private:
+  const people* p_;
+  people::const_iterator i_;
+};
+  
+ +

This code fragment should look familiar by now. Just note that + all the pre() callbacks now have arguments. Here is the + implementation of the test driver for this example:

+ +
+#include <iostream>
+
+using namespace std;
+
+int
+main ()
+{
+  // Create a sample object model.
+  //
+  people ppl;
+
+  ppl.push_back (person ("John", "Doe", male, 32));
+  ppl.push_back (person ("Jane", "Doe", female, 28));
+
+  // Construct the serializer.
+  //
+  xml_schema::short_simpl short_s;
+  xml_schema::string_simpl string_s;
+
+  gender_simpl gender_s;
+  person_simpl person_s;
+  people_simpl people_s;
+
+  person_s.serializers (string_s, string_s, gender_s, short_s);
+  people_s.serializers (person_s);
+
+  // Create the XML document.
+  //
+  xml_schema::document_simpl doc_s (people_s, "people");
+
+  people_s.pre (ppl);
+  doc_s.serialize (cout, xml_schema::document_simpl::pretty_print);
+  people_s.post ();
+}
+  
+ +

The serializer creation and assembly part is exactly the same as in + the previous chapter. The serialization part is a bit different: + people_simpl::pre() now has an argument which is the + complete object model. Also we write the resulting XML directly + to the standard output stream instead of first storing it in a string. + We can now save the last two code fragments to driver.cxx + and proceed to compile and test our new application:

+ + +
+$ c++ -I.../libxsde -c driver.cxx people-sskel.cxx
+$ c++ -o driver driver.o people-sskel.o .../libxsde/xsde/libxsde.a
+$ ./driver
+<people>
+  <person>
+    <first-name>John</first-name>
+    <last-name>Doe</last-name>
+    <gender>male</gender>
+    <age>32</age>
+  </person>
+  <person>
+    <first-name>Jane</first-name>
+    <last-name>Doe</last-name>
+    <gender>female</gender>
+    <age>28</age>
+  </person>
+</people>
+  
+ + + + +

5 Serializer Callbacks

+ +

In previous chapters we have learned that for each attribute + and element in a schema type there is a callback in a serializer + skeleton with the same name and which optionally returns + this element's or attribute's value. We've also seen that + elements that can appear multiple times + (maxOccurs="unbounded") have an additional + serializer callback in the form:

+ +
+virtual bool
+<name>_next ();
+  
+ +

Where <name> stands for the element's name. In + this chapter we will discuss other additional serializer + callbacks that are generated for certain XML Schema constructs. + We will also learn that besides elements and attributes, serializer + callback can be generated for the all, choice, + and sequence compositors as well as the any + and anyAttribute wildcards.

+ +

When additional serializer callback are generated for elements + and attributes, their names are derived from element's and + attribute's names. Compositors and wildcards, on the other + hand, do not have names and as a result the serializer + callback names for these constructs are based on synthesized + names in the form: all for the all + compositor, sequence, sequence1, + etc., for the sequence compositors, choice, + choice1, etc., for the choice compositors, + any, any1, etc., for the any + wildcards, and any_attribute, any_attribute1, + etc., for the anyAttribute wildcards. For example:

+ +
+<xs:complexType name="coordinates">
+  <xs:sequence maxOccurs="unbounded">
+    <xs:element name="lat" type="xs:float"/>
+    <xs:element name="lon" type="xs:float"/>
+  </xs:sequence>
+</xs:complexType>
+  
+ +

The above schema fragment, when compiled, results in the following + serializer skeleton:

+ +
+class coordinates_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  virtual void
+  pre ();
+
+  virtual bool
+  sequence_next ();
+
+  virtual float
+  lan () = 0;
+
+  virtual float
+  lon () = 0;
+
+  virtual void
+  post ();
+
+  ...
+};
+  
+ + +

5.1 Optional Callback

+ +

For elements, compositors, and element wildcards with the minimal + occurrence constraint equals 0 (minOccurs="0") + and the maximum occurrence constraint equals 1 + (maxOccurs="1") as well as for optional attributes, the + optional callback is generated in the form:

+ +
+virtual bool
+<name>_present ();
+  
+ +

This callback is called before any other callbacks for this schema + construct and if it returns false no further callback + calls corresponding to this construct are made and the corresponding + XML fragment is omitted. For example:

+ +
+<xs:complexType name="name">
+  <xs:sequence minOccurs="0">
+    <xs:element name="first" type="xs:string"/>
+    <xs:element name="initial" type="xs:string" minOccurs="0"/>
+    <xs:element name="last" type="xs:string"/>
+  </xs:sequence>
+  <xs:attribute name="lang" type="xs:language"/>
+</xs:complexType>
+  
+ +

The above schema fragment, when compiled, results in the following + serializer skeleton:

+ +
+class name_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  virtual void
+  pre ();
+
+  virtual bool
+  lang_present ();
+
+  virtual std::string
+  lang () = 0;
+
+  virtual bool
+  sequence_present ();
+
+  virtual std::string
+  first () = 0;
+
+  virtual bool
+  initial_present ();
+
+  virtual std::string
+  initial () = 0;
+
+  virtual std::string
+  last () = 0;
+
+  virtual void
+  post ();
+
+  ...
+};
+  
+ +

5.2 Sequence Callback

+ +

For elements, compositors, and element wildcards with the the maximum + occurrence constraint greater than 1 (for example, + maxOccurs="unbounded") the sequence callback is + generated in the form:

+ +
+virtual bool
+<name>_next ();
+  
+ +

This callback is called before each new item of the sequence is + about to be serialized. Returning false from this + callback indicates that no more items in the sequence need to + be serialized. For example:

+ +
+<xs:complexType name="names">
+  <xs:sequence maxOccurs="unbounded">
+    <xs:element name="first" type="xs:string"/>
+    <xs:element name="last" type="xs:string"/>
+    <xs:element name="pseudonym" type="xs:string" maxOccurs="3"/>
+  </xs:sequence>
+</xs:complexType>
+  
+ +

The above schema fragment, when compiled, results in the following + serializer skeleton:

+ +
+class names_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  virtual void
+  pre ();
+
+  virtual bool
+  sequence_next () = 0;
+
+  virtual std::string
+  first () = 0;
+
+  virtual std::string
+  last () = 0;
+
+  virtual bool
+  pseudonym_next () = 0;
+
+  virtual std::string
+  pseudonym () = 0;
+
+  virtual void
+  post ();
+};
+  
+ +

5.3 Choice Callback

+ +

The choice compositor allows an XML document to contain one + of several element or compositor options. In the Embedded + C++/Serializer mapping, these options are called choice + arms and are identified by the arm tags. For + example:

+ +
+<xs:complexType name="name">
+  <xs:choice>
+    <xs:element name="full-name" type="xs:string"/>
+    <xs:sequence>
+      <xs:element name="first-name" type="xs:string"/>
+      <xs:element name="last-name" type="xs:string"/>
+    </xs:sequence>
+  </xs:choice>
+</xs:complexType>
+  
+ +

The above schema fragment, when compiled, results in the following + serializer skeleton:

+ +
+class name_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  virtual void
+  pre ();
+
+  enum choice_arm_tag
+  {
+    full_name_tag,
+    sequence_tag
+  };
+
+  virtual choice_arm_tag
+  choice_arm () = 0;
+
+  virtual std::string
+  full_name () = 0;
+
+  virtual std::string
+  first_name () = 0;
+
+  virtual std::string
+  last_name () = 0;
+
+  virtual void
+  post ();
+};
+  
+ +

The arm tags enum name (choice_arm_tag above) is derived + from the choice compositor name (that is, choice, + choice1, etc.) by adding the _arm_tag + suffix. The tag names themselves are derived from the corresponding + elements, compositors, or element wildcards.

+ +

The choice compositor callback has a name in the form + choice_tag() (or choice1_tag(), etc., for + subsequent choice compositors in the type). It returns + the arm tag which identifies the choice arm that should be + serialized. For example, if a name_sskel implementation + returns full_name_tag from the choice_arm() + callback, then the first choice arm is chosen and + the full_name() callback is then called. Otherwise + the first_name and last_name() callbacks + are called.

+ + +

5.4 Element Wildcard Callbacks

+ +

An element wildcard allows an arbitrary element from the specified + namespace list to be present in an XML instance. Element wildcards + can have the same cardinality constraints as elements and, as as a + result, the optional or sequence callbacks can be generated. For + example:

+ +
+<xs:complexType name="name">
+  <xs:sequence>
+    <xs:element name="first" type="xs:string"/>
+    <xs:element name="last" type="xs:string"/>
+    <xs:any namespace="##other" processContents="skip" minOccurs="0"/>
+  </xs:sequence>
+</xs:complexType>
+  
+ +

The above schema fragment, when compiled, results in the following + serializer skeleton:

+ +
+class name_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  virtual void
+  pre ();
+
+  virtual std::string
+  first () = 0;
+
+  virtual std::string
+  last () = 0;
+
+  virtual bool
+  any_present ();
+
+  virtual void
+  any (std::string& ns, std::string& name);
+
+  virtual void
+  serialize_any ();
+
+  virtual void
+  post ();
+};
+  
+ +

The any() callback is called to obtain the element + name and namespace. If validation is enabled, the namespace is + checked against the allowed list. Then an element with these name + and namespace is created and the serialize_any() + callback is called to allow you to serialize the element's attributes + and content. There are two common ways to serialize a wildcard + element. The first approach is to use a serializer implementation. + This approach is shown in the wildcard example which + is part of the XSD/e distribution. The other approach is to use + the low-level XML serialization API that is available to every + serializer implementation via the + xml_schema::serializer_base base serializer:

+ +
+namespace xml_schema
+{
+  class serializer_base
+  {
+  public:
+    void
+    _start_element (const char* name);
+
+    void
+    _start_element (const char* ns, const char* name);
+
+    void
+    _end_element ();
+
+    void
+    _start_attribute (const char* name);
+
+    void
+    _start_attribute (const char* ns, const char* name);
+
+    void
+    _end_attribute ();
+
+    void
+    _attribute (const char* name, const char* value);
+
+    void
+    _attribute (const char* ns, const char* name, const char* value);
+
+    void
+    _characters (const char*);
+
+    void
+    _characters (const char*, size_t);
+
+    void
+    _declare_namespace (const char* ns, const char* prefix);
+
+    void
+    _declare_default_namespace (const char* ns);
+
+    void
+    _clear_default_namespace ();
+  };
+}
+  
+ +

The following example shows how we could implement the + name_sskel skeleton using this approach:

+ +
+class name_simpl: public name_sskel
+{
+public:
+  virtual std::string
+  first ()
+  {
+    return "John";
+  }
+
+  virtual ::std::string
+  last ()
+  {
+    return "Doe";
+  }
+
+  virtual bool
+  any_present ()
+  {
+    return true;
+  }
+
+  virtual void
+  any (std::string& ns, std::string& name)
+  {
+    ns = "http://www.example.com/extension";
+    name = "pseudonyms";
+  }
+
+  virtual void
+  serialize_any ()
+  {
+    _attribute ("id", "jd");
+
+    _start_element ("pseudonym");
+    _characters ("Johnny Doer");
+    _end_element ();
+
+    _start_element ("pseudonym");
+    _characters ("Johnty Doo");
+    _end_element ();
+  }
+};
+  
+ + +

5.5 Attribute Wildcard Callbacks

+ +

An attribute wildcard allows an arbitrary number of attributes from + the specified namespace list to be present in an XML instance. As a + result, the serializer callbacks for an attribute wildcard resemble + those of an element with maxOccurs="unbounded". For + example:

+ +
+<xs:complexType name="name">
+  <xs:sequence>
+    <xs:element name="first" type="xs:string"/>
+    <xs:element name="last" type="xs:string"/>
+  </xs:sequence>
+  <xs:anyAttribute namespace="##any" processContents="skip"/>
+</xs:complexType>
+  
+ +

The above schema fragment, when compiled, results in the following + serializer skeleton:

+ +
+class name_sskel: public xml_schema::serializer_complex_content
+{
+public:
+  virtual void
+  pre ();
+
+  virtual bool
+  any_attribute_next ();
+
+  virtual void
+  any_attribute (std::string& ns, std::string& name);
+
+  virtual void
+  serialize_any_attribute ();
+
+  virtual std::string
+  first () = 0;
+
+  virtual std::string
+  last () = 0;
+
+  virtual void
+  post ();
+};
+  
+ +

Every time the any_attribute_next() callback returns + true, any_attribute() is called to obtain + the attribute name and namespace. If validation is enabled, the + namespace is checked against the allowed list. Then an attribute + with these name and namespace is created and the + serialize_any_attribute() callback is called to allow + you to write the attribute value, for example using one of the + serializer implementations (see the wildcard example + on how to do it) or the low-level _characters() function + (for more information about the low-level XML serialization + API see the previous section). The following example show + how we could implement the name_sskel skeleton + using the latter approach:

+ +
+class name_simpl: public name_sskel
+{
+public:
+  virtual void
+  pre ()
+  {
+    id_written_ = false;
+  }
+
+  virtual bool
+  any_attribute_next ()
+  {
+    return !id_written_;
+  }
+
+  virtual void
+  any_attribute (std::string& ns, std::string& name)
+  {
+    ns = "";
+    name = "id";
+  }
+
+  virtual void
+  serialize_any_attribute ()
+  {
+    _characters ("jd");
+    id_written_ = true;
+  }
+
+  virtual std::string
+  first ()
+  {
+    return "John";
+  }
+
+  virtual ::std::string
+  last ()
+  {
+    return "Doe";
+  }
+
+private:
+  bool id_written_;
+};
+  
+ + + + + +

6 Mapping Configuration

+ +

The Embedded C++/Serializer mapping has a number of configuration + parameters that determine the overall properties and behavior + of the generated code, such as the use of Standard Template + Library (STL), Input/Output Stream Library (iostream), C++ + exceptions, XML Schema validation, 64-bit integer types, serializer + implementation reuse styles, and support for XML Schema polymorphism. + Previous chapters assumed that the use of STL, iostream, C++ + exceptions, and XML Schema validation were enabled. + This chapter will discuss the changes in the Embedded C++/Serializer + programming model that result from the changes to these configuration + parameters. A complete example that uses the minimal mapping + configuration is presented at the end of this chapter.

+ +

In order to enable or disable a particular feature, the corresponding + configuration parameter should be set accordingly in the XSD/e runtime + library as well as specified during schema compilation with the XSD/e + command line options as described in the + XSD/e + Compiler Command Line Manual. +

+ +

The Embedded C++/Serializer mapping always expects character data + supplied by the application to be in the same encoding. The + application encoding can either be UTF-8 (default) or ISO-8859-1. + To select a particular encoding, configure the XSD/e runtime library + accordingly and pass the --char-encoding option to the + XSD/e compiler when translating your schemas. The underlying XML + serializer used by the Embedded C++/Serializer mapping produces + the resulting XML documents in the UTF-8 encoding.

+ +

6.1 Standard Template Library

+ +

To disable the use of STL you will need to configure the XSD/e + runtime without support for STL as well as pass the + --no-stl option to the XSD/e compiler when + translating your schemas. When STL is disabled, all string-based + XML Schema types are mapped to C-style const char* + instead of std::string, as described in + Section 4.2, "Type Map File Format". The + following code fragment shows changes in the + signatures of the first_name() and last_name() + callbacks from the person record example.

+ +
+class person_sskel
+{
+public:
+  virtual const char*
+  first_name ();
+
+  virtual const char*
+  last_name ();
+
+  ...
+};
+  
+ +

When STL is disabled, the serializer implementations for the string-based + built-in XML Schema types can be instructed to release the string + after serialization using operator delete[]. For more + information on how to do this refer to Section 7.2, + "String-Based Type Serializers". +

+ +

6.2 Input/Output Stream Library

+ +

To disable the use of iostream you will need to configure the + XSD/e runtime library without support for iostream as well as + pass the --no-iostream option to the XSD/e compiler + when translating your schemas. When iostream is disabled, the + following serialize() function in the + xml_schema::document_simpl class become unavailable:

+ +
+void
+serialize (std::ostream&, flags);
+  
+ +

See Section 8.1, "Document Serializer" + for more information.

+ +

6.3 C++ Exceptions

+ +

To disable the use of C++ exceptions, you will need to configure + the XSD/e runtime without support for exceptions as well as pass + the --no-exceptions option to the XSD/e compiler + when translating your schemas. When C++ exceptions are disabled, + the error conditions are indicated with error codes instead of + exceptions, as described in Section 8.3, + "Error Codes". +

+ +

6.4 XML Schema Validation

+ +

To disable support for XML Schema validation, you will need to + configure the XSD/e runtime accordingly as well as pass + the --suppress-validation option to the XSD/e compiler + when translating your schemas. Disabling XML Schema validation + allows to further increase the serialization performance and + reduce footprint in cases where the data being serialized is + known to be valid. +

+ +

6.5 64-bit Integer Type

+ +

By default the 64-bit long and unsignedLong + XML Schema built-in types are mapped to the 64-bit long long + and unsigned long long fundamental C++ types. To + disable the use of these types in the mapping you will need to + configure the XSD/e runtime accordingly as well as pass + the --no-long-long option to the XSD/e compiler + when translating your schemas. When the use of 64-bit integral + C++ types is disabled the long and + unsignedLong XML Schema built-in types are mapped + to long and unsigned long fundamental + C++ types.

+ +

6.6 Serializer Reuse

+ +

When one type in XML Schema inherits from another, it is + often desirable to be able to reuse the serializer implementation + corresponding to the base type in the serializer implementation + corresponding to the derived type. XSD/e provides support + for two serializer reuse styles: the so-called mixin + (generated when the --reuse-style-mixin option + is specified) and tiein (generated by default) styles.

+ +

The compiler can also be instructed not to generate any support + for serializer reuse with the --reuse-style-none option. + This is mainly useful to further reduce the generated code size + when your vocabulary does not use inheritance or when you plan + to implement each serializer from scratch. Note also that the + XSD/e runtime should be configured in accordance with the + serializer reuse style used in the generated code. The remainder + of this section discusses the mixin and tiein serializer reuse + styles in more detail.

+ + +

To provide concrete examples for each reuse style we will use the + following schema fragment:

+ +
+<xs:complexType name="person">
+  <xs:sequence>
+    <xs:element name="first-name" type="xs:string"/>
+    <xs:element name="last-name" type="xs:string"/>
+    <xs:element name="age" type="xs:short"/>
+  </xs:sequence>
+</xs:complexType>
+
+<xs:complexType name="emplyee">
+  <complexContent>
+    <extension base="person">
+      <xs:sequence>
+        <xs:element name="position" type="xs:string"/>
+        <xs:element name="salary" type="xs:unsignedLong"/>
+      </xs:sequence>
+    </extension>
+  </complexContent>
+</xs:complexType>
+  
+ +

The mixin serializer reuse style uses the C++ mixin idiom that + relies on multiple and virtual inheritance. Because + virtual inheritance can result in a significant object + code size increase, this reuse style should be considered + when such an overhead is acceptable and/or the vocabulary + consists of only a handful of types. When the mixin reuse + style is used, the generated serializer skeletons use virtual + inheritance, for example:

+ +
+class person_sskel: public virtual serializer_complex_content
+{
+  ...
+};
+
+class employee_sskel: public virtual person_sskel
+{
+  ...
+};
+  
+ + +

When you implement the base serializer you also need to use + virtual inheritance. The derived serializer is implemented + by inheriting from both the derived serializer skeleton and + the base serializer implementation (that is, mixing in + the base serializer implementation), for example:

+ +
+class person_simpl: public virtual person_sskel
+{
+  ...
+};
+
+class employee_simpl: public employee_sskel,
+                      public person_simpl
+{
+  ...
+};
+  
+ + +

The tiein serializer reuse style uses delegation and normally + results in a significantly smaller object code while being + almost as convenient to use as the mixin style. When the + tiein reuse style is used, the generated derived serializer + skeleton declares a constructor which allows you to specify + the implementation of the base serializer:

+ +
+class person_sskel: public serializer_complex_content
+{
+  ...
+};
+
+class employee_sskel: public person_sskel
+{
+public:
+  employee_sskel (person_sskel* base_impl)
+
+  ...
+};
+  
+ +

If you pass the implementation of the base serializer to this + constructor then the generated code will transparently + forward all the callbacks corresponding to the base serializer + skeleton to this implementation. You can also pass + 0 to this constructor in which case you will + need to implement the derived serializer from scratch. The + following example shows how we could implement the + person and employee serializers + using the tiein style:

+ +
+class person_simpl: public person_sskel
+{
+  ...
+};
+
+class employee_simpl: public employee_sskel
+{
+public:
+  employee_simpl ()
+    : employee_sskel (&base_impl_)
+  {
+  }
+
+  ...
+
+private:
+  person_simpl base_impl_;
+};
+  
+ +

Note that you cannot use the tied in base serializer + instance (base_impl_ in the above code) for + serializing anything except the derived type.

+ +

The ability to override the base serializer callbacks in the + derived serializer is also available in the tiein style. For + example, the following code fragment shows how we can + override the age() callback if we didn't + like the implementation provided by the base serializer:

+ +
+class employee_simpl: public employee_sskel
+{
+public:
+  employee_simpl ()
+    : employee_sskel (&base_impl_)
+  {
+  }
+
+  virtual short
+  age ()
+  {
+    ...
+  }
+
+  ...
+
+private:
+  person_simpl base_impl_;
+};
+  
+ +

In the above example the age element will be + handled by emplyee_simpl while the first-name + and last-name callbacks will still go to + base_impl_.

+ +

It is also possible to inherit from the base serializer implementation + instead of declaring it as a member variable. This can be useful + if you need to access protected members in the base implementation + or need to override a virtual function that is not part of + the serializer skeleton interface. Note, however, that in this case + you will need to resolve a number of ambiguities with explicit + qualifications or using-declarations. For example:

+ + +
+class person_simpl: public person_sskel
+{
+public:
+  virtual void
+  pre (person* p)
+  {
+    person_ = p;
+  }
+
+  ...
+
+protected:
+  person* person_;
+};
+
+class employee_simpl: public employee_sskel,
+                      public person_simpl
+{
+public:
+  employee_simpl ()
+    : employee_sskel (static_cast<person_simpl*> (this))
+  {
+  }
+
+  // Resolve ambiguities.
+  //
+  using emplyee_sskel::serializers;
+
+  virtual void
+  pre (employee* e)
+  {
+    person_simpl::pre (e);
+  }
+
+  virtual std::string
+  position ()
+  {
+    return static_cast<employee*> (person_)->position ();
+  }
+
+  virtual unsigned int
+  salary ()
+  {
+    return static_cast<employee*> (person_)->salary ();
+  }
+};
+  
+ +

6.7 Support for Polymorphism

+ +

By default the XSD/e compiler generates non-polymorphic code. If your + vocabulary uses XML Schema polymorphism in the form of xsi:type + and/or substitution groups, then you will need to configure the XSD/e + runtime with support for polymorphism, compile your schemas with the + --generate-polymorphic option to produce polymorphism-aware + code, as well as pass true as the last argument to the + xml_schema::document's constructors. If some of your + schemas do not require support for polymorphism then you can compile + them with the --runtime-polymorphic option and still + use the XSD/e runtime configured with polymorphism support. +

+ +

When using the polymorphism-aware generated code, you can specify + several serializers for a single element by passing a serializer map + instead of an individual serializer to the serializer connection function + for the element. One of the serializers will then be looked up and used + depending on the user-provided type information that can optionally be + set in the callback function for the element. Consider the following + schema as an example:

+ +
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <xs:complexType name="person">
+    <xs:sequence>
+      <xs:element name="name" type="xs:string"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <!-- substitution group root -->
+  <xs:element name="person" type="person"/>
+
+  <xs:complexType name="superman">
+    <xs:complexContent>
+      <xs:extension base="person">
+        <xs:attribute name="can-fly" type="xs:boolean"/>
+      </xs:extension>
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:element name="superman"
+              type="superman"
+              substitutionGroup="person"/>
+
+  <xs:complexType name="batman">
+    <xs:complexContent>
+      <xs:extension base="superman">
+        <xs:attribute name="wing-span" type="xs:unsignedInt"/>
+      </xs:extension>
+    </xs:complexContent>
+  </xs:complexType>
+
+  <xs:complexType name="supermen">
+    <xs:sequence>
+      <xs:element ref="person" maxOccurs="unbounded"/>
+    </xs:sequence>
+  </xs:complexType>
+
+  <xs:element name="supermen" type="supermen"/>
+
+</xs:schema>
+  
+ +

Conforming XML documents can use the superman + and batman types in place of the person + type either by specifying the type with the xsi:type + attributes or by using the elements from the substitution + group, for instance:

+ +
+<supermen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+
+  <person>
+    <name>John Doe</name>
+  </person>
+
+  <superman can-fly="false">
+    <name>James "007" Bond</name>
+  </superman>
+
+  <person can-fly="true" wing-span="10" xsi:type="batman">
+    <name>Bruce Wayne</name>
+  </person>
+
+</supermen>
+  
+ +

The C++ object model for this vocabulary might look as follows:

+ +
+#include <string>
+#include <vector>
+
+enum type_id
+{
+  person_type,
+  superman_type,
+  batman_type
+};
+
+class person
+{
+public:
+  virtual
+  ~person () {}
+
+  person (const std::string& name)
+      : name_ (name)
+  {
+  }
+
+  const std::string&
+  name () const
+  {
+    return name_;
+  }
+
+  void
+  name (const std::string& n)
+  {
+    name_ = n;
+  }
+
+  virtual type_id
+  type () const
+  {
+    return person_type;
+  }
+
+private:
+  std::string name_;
+};
+
+class superman: public person
+{
+public:
+  superman (const std::string& name, bool can_fly)
+      : person (name), can_fly_ (can_fly)
+  {
+  }
+
+  bool
+  can_fly () const
+  {
+    return can_fly_;
+  }
+
+  void
+  can_fly (bool cf)
+  {
+    can_fly_ = cf;
+  }
+
+  virtual type_id
+  type () const
+  {
+    return superman_type;
+  }
+
+private:
+  bool can_fly_;
+};
+
+class batman: public superman
+{
+public:
+  batman (const std::string& name, unsigned int wing_span)
+      : superman (name, true), wing_span_ (wing_span)
+  {
+  }
+
+  unsigned int
+  wing_span () const
+  {
+    return wing_span_;
+  }
+
+  void
+  wing_span (unsigned int ws)
+  {
+    wing_span_ = ws;
+  }
+
+  virtual type_id
+  type () const
+  {
+    return batman_type;
+  }
+
+private:
+  unsigned int wing_span_;
+};
+
+// Poor man's polymorphic sequence which also assumes ownership
+// of the elements.
+//
+class supermen: public std::vector<person*>
+{
+public:
+  ~supermen ()
+  {
+    for (iterator i = begin (); i != end (); ++i)
+      delete *i;
+  }
+};
+  
+ +

Here we choose to provide our own type information. We can instead + use the standard C++ typeid/type_info + mechanism if it is available. The type map corresponding to this + object model is presented below. Notice that the superman + and batman objects are passed as a reference to + person:

+ +
+person   "const ::person&";
+superman "const ::person&";
+batman   "const ::person&";
+supermen "const ::supermen&";
+  
+ +

The serializer implementations that serialize the above + C++ object model to XML are presented next:

+ +
+class person_simpl: public person_sskel
+{
+public:
+  virtual void
+  pre (const person& p)
+  {
+    person_ = &p;
+  }
+
+  virtual std::string
+  name ()
+  {
+    return person_->name ();
+  }
+
+  // Derived serializer implementations need access to this
+  // member variable.
+  //
+public:
+  const person* person_;
+};
+
+class superman_simpl: public superman_sskel
+{
+public:
+  superman_simpl ()
+    : superman_sskel (&base_impl_)
+  {
+  }
+
+  virtual bool
+  can_fly ()
+  {
+    return superman_ ().can_fly ();
+  }
+
+  const superman&
+  superman_ ()
+  {
+    return *static_cast<const superman*> (base_impl_.person_);
+  }
+
+private:
+  person_simpl base_impl_;
+};
+
+class batman_simpl: public batman_sskel
+{
+public:
+  batman_simpl ()
+    : batman_sskel (&base_impl_)
+  {
+  }
+
+  virtual unsigned int
+  wing_span ()
+  {
+    return batman_ ().wing_span ();
+  }
+
+  const batman&
+  batman_ ()
+  {
+    return static_cast<const batman&> (base_impl_.superman_ ());
+  }
+
+private:
+  superman_simpl base_impl_;
+};
+
+class supermen_simpl: public supermen_sskel
+{
+public:
+  virtual void
+  pre (const supermen& s)
+  {
+    supermen_ = &s;
+    i_ = s.begin ();
+  }
+
+  virtual bool
+  person_next ()
+  {
+    return i_ != supermen_->end ();
+  }
+
+  virtual const ::person&
+  person ()
+  {
+    const ::person& p = **i_++;
+    xml_schema::serializer_context& ctx = _context ();
+
+    switch (p.type ())
+    {
+    case person_type:
+      {
+        ctx.type_id (person_sskel::_static_type ());
+        break;
+      }
+    case superman_type:
+      {
+        ctx.type_id (superman_sskel::_static_type ());
+        break;
+      }
+    case batman_type:
+      {
+        ctx.type_id (batman_sskel::_static_type ());
+        break;
+      }
+    }
+
+    return p;
+  }
+
+private:
+  const supermen* supermen_;
+  supermen::const_iterator i_;
+};
+  
+ +

Most of the code in these serializer implementations is the same + as in the non-polymorphic case. The only part that explicitly deals + with polymorphism is the person() callback in the + superman_simpl class. In it we are translating + the type information as provided by the C++ object mode to + the type information used in the default implementation of + the serializer map (we will talk more about serializer maps + as well as the _static_type() function shortly). + The type_id() function from + xml_schema::serializer_context allows you to + specify optional type information which is used to look up + the corresponding serializer. Its argument is of type + const void* which allows you to pass + application-specific type information as an opaque pointer.

+ +

The following code fragment shows how to connect the serializers + together and then use them to serialize a sample object model. + Notice that for the person element in the + instance_s serializer we specify a serializer map + instead of a specific serializer and we pass true as + the last argument to the document serializer constructor to indicate + that we are serializing potentially-polymorphic XML documents:

+ +
+int
+main ()
+{
+  // Create a sample supermen catalog. To keep things simple
+  // the following code is not exception-safe.
+  //
+  supermen sm;
+
+  sm.push_back (new person ("John Doe"));
+  sm.push_back (new superman ("James 007 Bond", false));
+  sm.push_back (new batman ("Bruce Wayne", 10));
+
+  // Construct the serializer.
+  //
+  xml_schema::string_simpl string_s;
+  xml_schema::boolean_simpl boolean_s;
+  xml_schema::unsigned_int_simpl unsigned_int_s;
+
+  person_simpl person_s;
+  superman_simpl superman_s;
+  batman_simpl batman_s;
+
+  xml_schema::serializer_map_impl person_map (5); // 5 hashtable buckets
+  supermen_simpl supermen_s;
+
+  person_s.serializers (string_s);
+  superman_s.serializers (string_s, boolean_s);
+  batman_s.serializers (string_s, boolean_s, unsigned_int_s);
+
+  // Here we are specifying several serializers that can be
+  // used to serialize the person element.
+  //
+  person_map.insert (person_s);
+  person_map.insert (superman_s);
+  person_map.insert (batman_s);
+
+  supermen_s.person_serializer (person_map);
+
+  // Create the XML instance document. The last argument to the
+  // document's constructor indicates that we are serializing
+  // polymorphic XML documents.
+  //
+  xml_schema::document_simpl doc_s (supermen_s, "supermen", true);
+
+  supermen_s.pre (sm);
+  doc_s.serialize (std::cout, xml_schema::document_simpl::pretty_print);
+  supermen_s.post ();
+}
+  
+ +

When polymorphism-aware code is generated, each element's + *_serializer() function is overloaded to also accept + an object of the xml_schema::serializer_map type. + For example, the supermen_sskel class from the + above example looks like this:

+ +
+class supermen_sskel: public xml_schema::serializer_complex_content
+{
+public:
+
+  ...
+
+  // Serializer construction API.
+  //
+  void
+  serializers (person_sskel&);
+
+  // Individual element serializers.
+  //
+  void
+  person_serializer (person_sskel&);
+
+  void
+  person_serializer (xml_schema::serializer_map&);
+
+  ...
+};
+  
+ +

Note that you can specify both the individual (static) serializer and + the serializer map. The individual serializer will be used when the static + element type and the dynamic type of the object being serialized are + the same. This is the case when the type_id() function + hasn't been called or the type information pointer is set to + 0. Because the individual serializer for an element + is cached and no map lookup is necessary, it makes sense to specify + both the individual serializer and the serializer map when most of + the objects being serialized are of the static type and optimal + performance is important. The following code fragment shows how + to change the above example to set both the individual serializer + and the serializer map:

+ +
+int
+main ()
+{
+  ...
+
+  // Here we are specifying several serializers that can be
+  // used to serialize the person element.
+  //
+  person_map.insert (superman_s);
+  person_map.insert (batman_s);
+
+  supermen_s.person_serializer (person_s);
+  supermen_s.person_serializer (person_map);
+
+  ...
+}
+  
+ + +

The xml_schema::serializer_map interface and its + default implementation, xml_schema::serializer_map_impl, + are presented below:

+ +
+namespace xml_schema
+{
+  class serializer_map
+  {
+  public:
+    virtual serializer_base*
+    find (const void* type_id) const = 0;
+
+    virtual void
+    reset () const = 0;
+  };
+
+  class serializer_map_impl: public serializer_map
+  {
+  public:
+    serializer_map_impl (size_t buckets);
+
+    // Note that the type_id string is not copied so it should
+    // be valid for the lifetime of the map.
+    //
+    void
+    insert (const char* type_id, serializer_base&);
+
+    // This version of insert is a shortcut that uses the string
+    // returned by the serializer's _dynamic_type() function.
+    //
+    void
+    insert (serializer_base&);
+
+    virtual serializer_base*
+    find (const void* type_id) const;
+
+    virtual void
+    reset () const;
+
+  private:
+    serializer_map_impl (const serializer_map_impl&);
+
+    serializer_map_impl&
+    operator= (const serializer_map_impl&);
+
+    ...
+  };
+}
+  
+ +

The type_id argument in the find() virtual + function is the application-specific type information for the object + being serialized that is specified using the type_id() + function in the element callback. It is passed as an opaque + const void*. The reset() virtual function + is used to reset the serializers contained in the map (as opposed to + resetting or clearing the map itself). For more information on serializer + resetting refer to Section 8.4, "Reusing Serializers + after an Error".

+ +

The XSD/e runtime provides the default implementation for the + xml_schema::serializer_map interface, + xml_schema::serializer_map_impl, which uses a C string + (const char*) as type information. One way to + obtain a serializer's dynamic type in the form + "<name> <namespace>" with the space and the + namespace part absent if the type does not have a namespace + is to call the _dynamic_type() function on this + serializer. The static type can be obtained by calling the static + _static_type() function, for example + person_sskel::_static_type(). Both functions return + a C string (const char*) which is valid for as long + as the application is running.

+ +

The default serializer map implementation is a hashmap. It requires + that you specify the number of buckets it will contain and it does + not support automatic table resizing. To obtain good performance the + elements to buckets ratio should be between 0.7 and 0.9. It is also + recommended to use prime numbers for bucket counts: + 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, + 196613, 393241. +

+ +

If C++ exceptions are disabled (Section 5.3, + "C++ Exceptions"), the xml_schema::serializer_map_impl + class has the following additional error querying API. It can be used + to detect the out of memory errors after calls to the + serializer_map_impl's constructor and insert() + functions.

+ +
+namespace xml_schema
+{
+  class serializer_map_impl: public serializer_map
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    error
+    _error () const;
+
+    ...
+  };
+}
+  
+ +

You can also provide your own serializer map implementation which uses + custom type information. The following example shows how we can + implement our own serializer map for the above example that uses + the type information provided by the C++ object model:

+ +
+#include <map>
+
+class person_serializer_map: public xml_schema::serializer_map
+{
+public:
+ void
+ insert (person_sskel& p)
+ {
+   const char* dt = p._dynamic_type ();
+   type_id ti;
+
+   if (strcmp (dt, person_sskel::_static_type ()) == 0)
+     ti = person_type;
+   else if (strcmp (dt, superman_sskel::_static_type ()) == 0)
+     ti = superman_type;
+   else if (strcmp (dt, batman_sskel::_static_type ()) == 0)
+     ti = batman_type;
+   else
+     return;
+
+   map_[ti] = &p;
+ }
+
+ virtual xml_schema::serializer_base*
+ find (const char* x) const
+ {
+   const person* p = static_cast<const person*> (x);
+   map::const_iterator i = map_.find (p->type ());
+   return i != map_.end () ? i->second : 0;
+ }
+
+ virtual void
+ reset () const
+ {
+   for (map::const_iterator i (map_.begin ()), e (map_.end ());
+        i != e; ++i)
+   {
+     person_sskel* s = i->second;
+     s->_reset ();
+   }
+ }
+
+private:
+  typedef std::map<type_id, person_sskel*> map;
+  map map_;
+};
+  
+ +

Our custom implementation of the serializer map expects that + we pass the actual object to the find() function. + To account for this will need to change the + supermen_simpl::person() callback as follows:

+ +
+  virtual const ::person&
+  person ()
+  {
+    const ::person& p = **i_++;
+    _context ().type_id (&p);
+    return p;
+  }
+  
+ + +

To support polymorphic serialization the XSD/e runtime and generated + code maintain a number of hashmaps that contain substitution and, if + XML Schema validation is enabled (Section 5.4, + "XML Schema Validation"), inheritance information. Because + the number of elements in these hashmaps depends on the schemas + being compiled and thus is fairly static, these hashmaps do not + perform automatic table resizing and instead the number of buckets + is specified when the XSD/e runtime is configured. To obtain good + performance the elements to buckets ratio in these hashmaps should + be between 0.7 and 0.9. The recommended way to ensure this range + is to add diagnostics code to your application as shown in the + following example:

+ +
+int
+main ()
+{
+  // Check that the load in substitution and inheritance hashmaps
+  // is not too high.
+  //
+#ifndef NDEBUG
+  float load = xml_schema::serializer_smap_elements ();
+  load /= xml_schema::serializer_smap_buckets ();
+
+  if (load > 0.8)
+  {
+    cerr << "substitution hashmap load is " << load << endl;
+    cerr << "time to increase XSDE_SERIALIZER_SMAP_BUCKETS" << endl;
+  }
+
+  load = xml_schema::serializer_smap_bucket_elements ();
+  load /= xml_schema::serializer_smap_bucket_buckets ();
+
+  if (load > 0.8)
+  {
+    cerr << "substitution inner hashmap load is " << load << endl;
+    cerr << "time to increase XSDE_SERIALIZER_SMAP_BUCKET_BUCKETS" << endl;
+  }
+
+  load = xml_schema::serializer_imap_elements ();
+  load /= xml_schema::serializer_imap_buckets ();
+
+  if (load > 0.8)
+  {
+    cerr << "inheritance hashmap load is " << load << endl;
+    cerr << "time to increase XSDE_SERIALIZER_IMAP_BUCKETS" << endl;
+  }
+#endif
+
+  ...
+}
+  
+ +

Most of the code presented in this section is taken from the + polymorphism example which can be found in the + examples/cxx/serializer/ directory of the XSD/e distribution. + Handling of xsi:type and substitution groups when used + on root elements requires a number of special actions as shown in + the polyroot example.

+ +

6.8 Custom Allocators

+ +

By default the XSD/e runtime and generated code use + the standard operators new and delete + to manage dynamic memory. However, it is possible to instead + use custom allocator functions provided by your application. + To achieve this, configure the XSD/e runtime library to use + custom allocator functions as well as pass the + --custom-allocator option to the XSD/e compiler + when translating your schemas. The signatures of the custom + allocator functions that should be provided by your application + are listed below. Their semantics should be equivalent to the + standard C malloc(), realloc(), and + free() functions.

+ +
+extern "C" void*
+xsde_alloc (size_t);
+
+extern "C" void*
+xsde_realloc (void*, size_t);
+
+extern "C" void
+xsde_free (void*);
+  
+ +

Note also that when custom allocators are enabled, any + dynamically-allocated object of which the XSD/e runtime + or generated code assume ownership should be allocated + using the custom allocation function. Similarly, if your + application assumes ownership of any dynamically-allocated + object returned by the XSD/e runtime or the generated code, + then such an object should be disposed of using the custom + deallocation function. To help with these tasks the generated + xml_schema namespace defines the following two + helper functions and, if C++ exceptions are enabled, automatic + pointer class:

+ +
+namespace xml_schema
+{
+  void*
+  alloc (size_t);
+
+  void
+  free (void*);
+
+  struct alloc_guard
+  {
+    alloc_guard (void*);
+    ~alloc_guard ();
+
+    void*
+    get () const;
+
+    void
+    release ();
+
+  private:
+    ...
+  };
+}
+  
+ +

If C++ exceptions are disabled, these functions are equivalent + to xsde_alloc() and xsde_free(). + If exceptions are enabled, xml_schema::alloc() + throws std::bad_alloc on memory allocation failure.

+ +

The following code fragment shows how to create and destroy a + dynamically-allocated object with custom allocators when C++ + exceptions are disabled:

+ +
+void* v = xml_schema::alloc (sizeof (type));
+
+if (v == 0)
+{
+  // Handle out of memory condition.
+}
+
+type* x = new (v) type (1, 2);
+
+...
+
+if (x)
+{
+  x->~type ();
+  xml_schema::free (x);
+}
+  
+ +

The equivalent code fragment for configurations with C++ exceptions + enabled is shown below:

+ +
+xml_schema::alloc_guard g (xml_schema::alloc (sizeof (type)));
+type* x = new (g.get ()) type (1, 2);
+g.release ();
+
+...
+
+if (x)
+{
+  x->~type ();
+  xml_schema::free (x);
+}
+  
+ +

6.9 A Minimal Example

+ +

The following example is a re-implementation of the person + records example presented in Chapter 4, + "Type Maps". It is intended to work without STL, + iostream, and C++ exceptions. It can be found in the + examples/cxx/serializer/minimal/ directory of the + XSD/e distribution. The people.xsd schema is + compiled with the --no-stl, --no-iostream, + and --no-exceptions options. The object model + types in people.hxx have also been reimplemented + in order not to use STL types:

+ +
+#include <stddef.h> // size_t
+
+enum gender
+{
+  male,
+  female
+};
+
+struct person
+{
+  const char* first_name_;
+  const char* last_name_;
+  gender gender_;
+  unsigned short age_;
+};
+
+struct people
+{
+  person* people_;
+  size_t size_;
+};
+  
+ + +

The following listing presents the implementation of serializer + skeletons and the test driver in full:

+ +
+#include <stdio.h>
+#include "people-sskel.hxx"
+
+const char* gender_strings[] = {"male", "female"};
+
+class gender_simpl: public gender_sskel
+{
+public:
+  gender_simpl ()
+    : gender_sskel (&base_impl_)
+  {
+  }
+
+  virtual void
+  pre (gender g)
+  {
+    base_impl_.pre (gender_strings[g]);
+  }
+
+private:
+  public xml_schema::string_simpl base_impl_;
+};
+
+class person_simpl: public person_sskel
+{
+public:
+  virtual void
+  pre (const person& p)
+  {
+    person_ = &p;
+  }
+
+  virtual const char*
+  first_name ()
+  {
+    return person_->first_name_;
+  }
+
+  virtual const char*
+  last_name ()
+  {
+    return person_->last_name_;
+  }
+
+  virtual ::gender
+  gender ()
+  {
+    return person_->gender_;
+  }
+
+  virtual unsigned short
+  age ()
+  {
+    return person_->age_;
+  }
+
+private:
+  const person* person_;
+};
+
+class people_simpl: public people_sskel
+{
+public:
+  virtual void
+  pre (const people& p)
+  {
+    i_ = 0;
+    people_ = &p;
+  }
+
+  virtual bool
+  person_next ()
+  {
+    return i_ < people_->size_;
+  }
+
+  virtual const ::person&
+  person ()
+  {
+    return people_->people_[i_++];
+  }
+
+private:
+  size_t i_;
+  const people* people_;
+};
+
+class writer: public xml_schema::writer
+{
+public:
+  virtual bool
+  write (const char* s, size_t n)
+  {
+    return fwrite (s, n, 1, stdout) == 1;
+  }
+
+  virtual bool
+  flush ()
+  {
+    return fflush (stdout) == 0;
+  }
+};
+
+int
+main ()
+{
+  // Create a sample person list.
+  //
+  people p;
+
+  p.size_ = 2;
+  p.people_ = new person[p.size_];
+
+  if (p.people_ == 0)
+  {
+    fprintf (stderr, "error: no memory\n");
+    return 1;
+  }
+
+  p.people_[0].first_name_ = "John";
+  p.people_[0].last_name_ = "Doe";
+  p.people_[0].gender_ = male;
+  p.people_[0].age_ = 32;
+
+  p.people_[1].first_name_ = "Jane";
+  p.people_[1].last_name_ = "Doe";
+  p.people_[1].gender_ = female;
+  p.people_[1].age_ = 28;
+
+  // Construct the serializer.
+  //
+  xml_schema::unsigned_short_simpl unsigned_short_s;
+  xml_schema::string_simpl string_s;
+
+  gender_simpl gender_s;
+  person_simpl person_s;
+  people_simpl people_s;
+
+  person_s.serializers (string_s, string_s, gender_s, unsigned_short_s);
+  people_s.serializers (person_s);
+
+  // Serialize.
+  //
+  typedef xml_schema::serializer_error error;
+
+  error e;
+  writer w;
+
+  do
+  {
+    xml_schema::document_simpl doc_s (people_s, "people");
+
+    if (e = doc_s._error ())
+      break;
+
+    people_s.pre (p);
+
+    if (e = people_s._error ())
+      break;
+
+    doc_s.serialize (w, xml_schema::document_simpl::pretty_print);
+
+    if (e = doc_s._error ())
+      break;
+
+    people_s.post ();
+
+    e = people_s._error ();
+
+  } while (false);
+
+  delete[] p.people_;
+
+  // Handle errors.
+  //
+  if (e)
+  {
+    switch (e.type ())
+    {
+    case error::sys:
+      {
+        fprintf (stderr, "error: %s\n", e.sys_text ());
+        break;
+      }
+    case error::xml:
+      {
+        fprintf (stderr, "error: %s\n", e.xml_text ());
+        break;
+      }
+    case error::schema:
+      {
+        fprintf (stderr, "error: %s\n", e.schema_text ());
+        break;
+      }
+    case error::app:
+      {
+        fprintf (stderr, "application error: %d\n", e.app_code ());
+        break;
+      }
+    default:
+      break;
+    }
+
+    return 1;
+  }
+
+  return 0;
+}
+  
+ + + + + +

7 Built-In XML Schema Type Serializers

+ +

The XSD/e runtime provides serializer implementations for all built-in + XML Schema types as summarized in the following table. Declarations + for these types are automatically included into each generated + header file. As a result you don't need to include any headers + to gain access to these serializer implementations.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XML Schema typeSerializer implementation in the xml_schema namespaceSerializer argument type
anyType and anySimpleType types
anyTypeany_type_simplvoid
anySimpleTypeany_simple_type_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
fixed-length integral types
bytebyte_simplsigned char
unsignedByteunsigned_byte_simplunsigned char
shortshort_simplshort
unsignedShortunsigned_short_simplunsigned short
intint_simplint
unsignedIntunsigned_int_simplunsigned int
longlong_simpllong long or long
+ Section 6.5, "64-bit Integer Type"
unsignedLongunsigned_long_simplunsigned long long or + unsigned long
+ Section 6.5, "64-bit Integer Type"
arbitrary-length integral types
integerinteger_simpllong
nonPositiveIntegernon_positive_integer_simpllong
nonNegativeIntegernon_negative_integer_simplunsigned long
positiveIntegerpositive_integer_simplunsigned long
negativeIntegernegative_integer_simpllong
boolean types
booleanboolean_simplbool
fixed-precision floating-point types
floatfloat_simplfloat
+ Section 7.1, "Floating-Point Type Serializers"
doubledouble_simpldouble
+ Section 7.1, "Floating-Point Type Serializers"
arbitrary-precision floating-point types
decimaldecimal_simpldouble
+ Section 7.1, "Floating-Point Type Serializers"
string-based types
stringstring_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
normalizedStringnormalized_string_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
tokentoken_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
Namename_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
NMTOKENnmtoken_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
NCNamencname_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
languagelanguage_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
qualified name
QNameqname_simplconst xml_schema::qname& or
+ const xml_schema::qname*
+ Section 7.3, "QName Serializer"
ID/IDREF types
IDid_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
IDREFidref_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
list types
NMTOKENSnmtokens_simplconst xml_schema::string_sequence*
Section + 7.4, "NMTOKENS and IDREFS Serializers"
IDREFSidrefs_simplconst xml_schema::string_sequence*
Section + 7.4, "NMTOKENS and IDREFS Serializers"
URI types
anyURIuri_simplconst std::string& or
const char*
+ Section 7.2, "String-Based Type Serializers"
binary types
base64Binarybase64_binary_simplconst xml_schema::buffer*
+ Section 7.5, "base64Binary and + hexBinary Serializers"
hexBinaryhex_binary_simplconst xml_schema::buffer*
+ Section 7.5, "base64Binary and + hexBinary Serializers"
date/time types
datedate_simplconst xml_schema::date&
+ Section 7.7, "date Serializer"
dateTimedate_time_simplconst xml_schema::date_time&
+ Section 7.8, "dateTime Serializer"
durationduration_simplconst xml_schema::duration&
+ Section 7.9, "duration Serializer"
gDaygday_simplconst xml_schema::gday&
+ Section 7.10, "gDay Serializer"
gMonthgmonth_simplconst xml_schema::gmonth&
+ Section 7.11, "gMonth Serializer"
gMonthDaygmonth_day_simplconst xml_schema::gmonth_day&
+ Section 7.12, "gMonthDay Serializer"
gYeargyear_simplconst xml_schema::gyear&
+ Section 7.13, "gYear Serializer"
gYearMonthgyear_month_simplconst xml_schema::gyear_month&
+ Section 7.14, "gYearMonth Serializer"
timetime_simplconst xml_schema::time&
+ Section 7.15, "time Serializer"
+ +

7.1 Floating-Point Type Serializers

+ +

The serializer implementations for the float, + double, and decimal built-in + XML Schema types allow you to specify the resulting + notation (fixed or scientific) as well as precision. + This is done by passing the corresponding arguments + to their constructors:

+ +
+namespace xml_schema
+{
+  class float_simpl: public float_sskel
+  {
+    enum notation
+    {
+      notation_auto,
+      notation_fixed,
+      notation_scientific
+    };
+
+    float_simpl (notation = notation_auto,
+                 unsigned int precision = FLT_DIG);
+
+    virtual void
+    pre (float);
+
+    ...
+  };
+
+  class double_simpl: public double_sskel
+  {
+    enum notation
+    {
+      notation_auto,
+      notation_fixed,
+      notation_scientific
+    };
+
+    double_simpl (notation = notation_auto,
+                  unsigned int precision = DBL_DIG);
+
+    virtual void
+    pre (double);
+
+    ...
+  };
+
+  class decimal_simpl: public decimal_sskel
+  {
+    decimal_simpl (unsigned int precision = DBL_DIG);
+
+    virtual void
+    pre (double);
+
+    ...
+  };
+}
+  
+ +

By default the notation for the float and double + types is automatically selected to produce the shortest representation. + Note that the decimal values are always serialized in + the fixed-point notation.

+ +

7.2 String-Based Type Serializers

+ +

When STL is enabled (Section 6.1, "Standard Template + Library"), the serializer argument type for the string, + normalizedString, token, + Name, NMTOKEN, NCName, + ID, IDREF, language, + anyURI, and anySimpleType built-in XML Schema + types is + const std::string&. When STL is disabled, the value + is passed as a constant C-string: const char*. + In this case, you can also instruct the serializer + implementations for string-based types to release the + string with operator delete[] by passing + true to their constructors. For instance, + using the person records example from the previous chapter:

+ +
+class person_simpl: public person_sskel
+{
+public:
+  virtual const char*
+  first_name ()
+  {
+    char* r = new char[5];
+    strcpy (r, "John");
+    return r;
+  }
+
+  virtual const char*
+  last_name ()
+  {
+    char* r = new char[4];
+    strcpy (r, "Doe");
+    return r;
+  }
+
+  ...
+};
+
+int
+main ()
+{
+  // Construct the serializer.
+  //
+  xml_schema::unsigned_short_simpl unsigned_short_s;
+  xml_schema::string_simpl string_s (true); // Release the string passed.
+
+  gender_simpl gender_s;
+  person_simpl person_s;
+  people_simpl people_s;
+
+  person_s.serializers (string_s, string_s, gender_s, unsigned_short_s);
+
+  ...
+}
+  
+ +

7.3 QName Serializer

+ +

The argument type of the qname_simpl serializer + implementation is either const xml_schema::qname& + when STL is enabled (Section 6.1, "Standard Template + Library") or const xml_schema::qname* when STL + is disabled. The qname class represents an XML + qualified name. When the argument type is const + xml_schema::qname*, you can optionally instruct the + serializer to release the qname object with operator + delete by passing true to its + constructor.

+ +

With STL enabled, the qname type has the following + interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (const std::string& name);
+    qname (const std::string& prefix, const std::string& name);
+
+    void
+    swap (qname&);
+
+    const std::string&
+    prefix () const;
+
+    std::string&
+    prefix ();
+
+    void
+    prefix (const std::string&);
+
+    const std::string&
+    name () const;
+
+    std::string&
+    name ();
+
+    void
+    name (const std::string&);
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+  
+ +

When STL is disabled and C++ exceptions are enabled + (Section 6.3, "C++ Exceptions"), the + qname type has the following interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (char* name);
+    qname (char* prefix, char* name);
+
+    void
+    swap (qname&);
+
+  private:
+    qname (const qname&);
+
+    qname&
+    operator= (const qname&);
+
+  public:
+    char*
+    prefix ();
+
+    const char*
+    prefix () const;
+
+    void
+    prefix (char*);
+
+    void
+    prefix_copy (const char*);
+
+    char*
+    prefix_detach ();
+
+  public:
+    char*
+    name ();
+
+    const char*
+    name () const;
+
+    void
+    name (char*);
+
+    void
+    name_copy (const char*);
+
+    char*
+    name_detach ();
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+
+ +

The modifier functions and constructors that have the char* + argument assume ownership of the passed strings which should be allocated + with operator new char[] and will be deallocated with + operator delete[] by the qname object. + If you detach the underlying prefix or name strings, then they + should eventually be deallocated with operator delete[]. +

+ +

Finally, if both STL and C++ exceptions are disabled, the + qname type has the following interface:

+ +
+namespace xml_schema
+{
+  class qname
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    qname ();
+
+    explicit
+    qname (char* name);
+    qname (char* prefix, char* name);
+
+    void
+    swap (qname&);
+
+  private:
+    qname (const qname&);
+
+    qname&
+    operator= (const qname&);
+
+  public:
+    char*
+    prefix ();
+
+    const char*
+    prefix () const;
+
+    void
+    prefix (char*);
+
+    error
+    prefix_copy (const char*);
+
+    char*
+    prefix_detach ();
+
+  public:
+    char*
+    name ();
+
+    const char*
+    name () const;
+
+    void
+    name (char*);
+
+    error
+    name_copy (const char*);
+
+    char*
+    name_detach ();
+  };
+
+  bool
+  operator== (const qname&, const qname&);
+
+  bool
+  operator!= (const qname&, const qname&);
+}
+  
+ +

7.4 NMTOKENS and IDREFS Serializers

+ +

The argument type of the nmtokens_simpl and + idrefs_simpl serializer implementations is + const xml_schema::string_sequence*. You can + optionally instruct these serializers to release the + string_sequence object with operator delete + by passing true to their constructors. With STL and C++ exceptions enabled + (Section 6.1, "Standard Template Library", + Section 6.3, "C++ Exceptions"), the + string_sequence type has the following interface:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    typedef std::string         value_type;
+    typedef std::string*        pointer;
+    typedef const std::string*  const_pointer;
+    typedef std::string&        reference;
+    typedef const std::string&  const_reference;
+
+    typedef size_t              size_type;
+    typedef ptrdiff_t           difference_type;
+
+    typedef std::string*        iterator;
+    typedef const std::string*  const_iterator;
+
+  public:
+    string_sequence ();
+
+    void
+    swap (string_sequence&);
+
+  private:
+    string_sequence (string_sequence&);
+
+    string_sequence&
+    operator= (string_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    std::string&
+    front ();
+
+    const std::string&
+    front () const;
+
+    std::string&
+    back ();
+
+    const std::string&
+    back () const;
+
+    std::string&
+    operator[] (size_t);
+
+    const std::string&
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    push_back (const std::string&);
+
+    iterator
+    insert (iterator, const std::string&);
+
+    void
+    reserve (size_t);
+  };
+
+  bool
+  operator== (const string_sequence&, const string_sequence&);
+
+  bool
+  operator!= (const string_sequence&, const string_sequence&);
+}
+  
+ +

When STL is enabled and C++ exceptions are disabled, the signatures + of the push_back(), insert(), and + reserve() functions change as follows:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (const std::string&);
+
+    error
+    insert (iterator, const std::string&);
+
+    error
+    insert (iterator, const std::string&, iterator& result);
+
+    error
+    reserve (size_t);
+  };
+}
+  
+ +

When STL is disabled and C++ exceptions are enabled, the + string_sequence type has the following interface:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    typedef char*         value_type;
+    typedef char**        pointer;
+    typedef const char**  const_pointer;
+    typedef char*         reference;
+    typedef const char*   const_reference;
+
+    typedef size_t        size_type;
+    typedef ptrdiff_t     difference_type;
+
+    typedef char** iterator;
+    typedef const char* const* const_iterator;
+
+    string_sequence ();
+
+    void
+    swap (string_sequence&);
+
+  private:
+    string_sequence (string_sequence&);
+
+    string_sequence&
+    operator= (string_sequence&);
+
+  public:
+    iterator
+    begin ();
+
+    const_iterator
+    begin () const;
+
+    iterator
+    end ();
+
+    const_iterator
+    end () const;
+
+    char*
+    front ();
+
+    const char*
+    front () const;
+
+    char*
+    back ();
+
+    const char*
+    back () const;
+
+    char*
+    operator[] (size_t);
+
+    const char*
+    operator[] (size_t) const;
+
+  public:
+    bool
+    empty () const;
+
+    size_t
+    size () const;
+
+    size_t
+    capacity () const;
+
+    size_t
+    max_size () const;
+
+  public:
+    void
+    clear ();
+
+    void
+    pop_back ();
+
+    iterator
+    erase (iterator);
+
+    void
+    push_back (char*);
+
+    void
+    push_back_copy (const char*);
+
+    iterator
+    insert (iterator, char*);
+
+    void
+    reserve (size_t);
+
+    // Detach a string from the sequence at a given position.
+    // The string pointer at this position in the sequence is
+    // set to 0.
+    //
+    char*
+    detach (iterator);
+  };
+
+  bool
+  operator== (const string_sequence&, const string_sequence&);
+
+  bool
+  operator!= (const string_sequence&, const string_sequence&);
+}
+  
+ +

The push_back() and insert() functions + assume ownership of the passed string which should be allocated + with operator new char[] and will be deallocated + with operator delete[] by the string_sequence + object. These two functions free the passed object if the reallocation + of the underlying sequence buffer fails. The push_back_copy() + function makes a copy of the passed string. + If you detach the underlying element string, then it should + eventually be deallocated with operator delete[].

+ +

When both STL and C++ exceptions are disabled, the signatures + of the push_back(), push_back_copy(), + insert(), and reserve() functions change + as follows:

+ +
+namespace xml_schema
+{
+  class string_sequence
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_no_memory
+    };
+
+    ...
+
+  public:
+    error
+    push_back (char*);
+
+    error
+    push_back_copy (const char*);
+
+    error
+    insert (iterator, char*);
+
+    error
+    insert (iterator, char*, iterator& result);
+
+    error
+    reserve (size_t);
+  };
+}
+  
+ + +

7.5 base64Binary and hexBinary Serializers

+ +

The argument type of the base64_binary_simpl and + hex_binary_simpl serializer implementations is + const xml_schema::buffer*. You can optionally + instruct these serializers to release the buffer + object with operator delete by passing true + to their constructors. With C++ exceptions enabled (Section + 6.3, "C++ Exceptions"), the buffer type has the + following interface:

+ +
+namespace xml_schema
+{
+  class buffer
+  {
+  public:
+    class bounds {}; // Out of bounds exception.
+
+  public:
+    buffer ();
+
+    explicit
+    buffer (size_t size);
+    buffer (size_t size, size_t capacity);
+    buffer (const void* data, size_t size);
+    buffer (const void* data, size_t size, size_t capacity);
+
+    enum ownership_value { assume_ownership };
+
+    // This constructor assumes ownership of the memory passed.
+    //
+    buffer (void* data, size_t size, size_t capacity, ownership_value);
+
+  private:
+    buffer (const buffer&);
+
+    buffer&
+    operator= (const buffer&);
+
+  public:
+    void
+    attach (void* data, size_t size, size_t capacity);
+
+    void*
+    detach ();
+
+    void
+    swap (buffer&);
+
+  public:
+    size_t
+    capacity () const;
+
+    bool
+    capacity (size_t);
+
+  public:
+    size_t
+    size () const;
+
+    bool
+    size (size_t);
+
+  public:
+    const char*
+    data () const;
+
+    char*
+    data ();
+
+    const char*
+    begin () const;
+
+    char*
+    begin ();
+
+    const char*
+    end () const;
+
+    char*
+    end ();
+  };
+
+  bool
+  operator== (const buffer&, const buffer&);
+
+  bool
+  operator!= (const buffer&, const buffer&);
+}
+  
+ +

The last constructor and the attach() member function + make the buffer instance assume the ownership of the + memory block pointed to by the data argument and + eventually release it by calling operator delete(). + The detach() member function detaches and returns the + underlying memory block which should eventually be released by + calling operator delete(). +

+ +

The capacity() and size() modifier functions + return true if the underlying buffer has moved. The + bounds exception is thrown if the constructor or + attach() member function arguments violate the + (size <= capacity) constraint.

+ +

If C++ exceptions are disabled, the buffer type has + the following interface:

+ +
+namespace xml_schema
+{
+  class buffer
+  {
+  public:
+    enum error
+    {
+      error_none,
+      error_bounds,
+      error_no_memory
+    };
+
+    buffer ();
+
+  private:
+    buffer (const buffer&);
+
+    buffer&
+    operator= (const buffer&);
+
+  public:
+    error
+    attach (void* data, size_t size, size_t capacity);
+
+    void*
+    detach ();
+
+    void
+    swap (buffer&);
+
+  public:
+    size_t
+    capacity () const;
+
+    error
+    capacity (size_t);
+
+    error
+    capacity (size_t, bool& moved);
+
+  public:
+    size_t
+    size () const;
+
+    error
+    size (size_t);
+
+    error
+    size (size_t, bool& moved);
+
+  public:
+    const char*
+    data () const;
+
+    char*
+    data ();
+
+    const char*
+    begin () const;
+
+    char*
+    begin ();
+
+    const char*
+    end () const;
+
+    char*
+    end ();
+  };
+
+  bool
+  operator== (const buffer&, const buffer&);
+
+  bool
+  operator!= (const buffer&, const buffer&);
+}
+  
+ +

7.6 Time Zone Representation

+ +

The date, dateTime, gDay, + gMonth, gMonthDay, gYear, + gYearMonth, and time XML Schema built-in + types all include an optional time zone component. The following + xml_schema::time_zone base class is used to represent + this information:

+ +
+namespace xml_schema
+{
+  class time_zone
+  {
+  public:
+    time_zone ();
+    time_zone (short hours, short minutes);
+
+    bool
+    zone_present () const;
+
+    void
+    zone_reset ();
+
+    short
+    zone_hours () const;
+
+    void
+    zone_hours (short);
+
+    short
+    zone_minutes () const;
+
+    void
+    zone_minutes (short);
+  };
+
+  bool
+  operator== (const time_zone&, const time_zone&);
+
+  bool
+  operator!= (const time_zone&, const time_zone&);
+}
+  
+ +

The zone_present() accessor function returns true + if the time zone is specified. The zone_reset() modifier + function resets the time zone object to the not specified + state. If the time zone offset is negative then both hours and + minutes components are represented as negative integers.

+ +

7.7 date Serializer

+ +

The argument type of the date_simpl serializer implementation + is const xml_schema::date&. The date class + represents a year, a day, and a month with an optional time zone. Its + interface is presented below. For more information on the base + xml_schema::time_zone class refer to Section + 7.6, "Time Zone Representation".

+ +
+namespace xml_schema
+{
+  class date: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    date ();
+
+    date (int year, unsigned short month, unsigned short day);
+
+    date (int year, unsigned short month, unsigned short day,
+          short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const date&, const date&);
+
+  bool
+  operator!= (const date&, const date&);
+}
+  
+ +

7.8 dateTime Serializer

+ +

The argument type of the date_time_simpl serializer + implementation is const xml_schema::date_time&. + The date_time class represents a year, a month, a day, + hours, minutes, and seconds with an optional time zone. Its interface + is presented below. For more information on the base + xml_schema::time_zone class refer to Section + 7.6, "Time Zone Representation".

+ +
+namespace xml_schema
+{
+  class date_time: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    date_time ();
+
+    date_time (int year, unsigned short month, unsigned short day,
+               unsigned short hours, unsigned short minutes,
+               double seconds);
+
+    date_time (int year, unsigned short month, unsigned short day,
+               unsigned short hours, unsigned short minutes,
+               double seconds, short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+
+    unsigned short
+    hours () const;
+
+    void
+    hours (unsigned short);
+
+    unsigned short
+    minutes () const;
+
+    void
+    minutes (unsigned short);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const date_time&, const date_time&);
+
+  bool
+  operator!= (const date_time&, const date_time&);
+}
+  
+ +

7.9 duration Serializer

+ +

The argument type of the duration_simpl serializer + implementation is const xml_schema::duration&. + The duration class represents a potentially + negative duration in the form of years, months, days, hours, minutes, + and seconds. Its interface is presented below.

+ +
+namespace xml_schema
+{
+  class duration
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    duration ();
+
+    duration (bool negative,
+              unsigned int years, unsigned int months, unsigned int days,
+              unsigned int hours, unsigned int minutes, double seconds);
+
+    bool
+    negative () const;
+
+    void
+    negative (bool);
+
+    unsigned int
+    years () const;
+
+    void
+    years (unsigned int);
+
+    unsigned int
+    months () const;
+
+    void
+    months (unsigned int);
+
+    unsigned int
+    days () const;
+
+    void
+    days (unsigned int);
+
+    unsigned int
+    hours () const;
+
+    void
+    hours (unsigned int);
+
+    unsigned int
+    minutes () const;
+
+    void
+    minutes (unsigned int);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const duration&, const duration&);
+
+  bool
+  operator!= (const duration&, const duration&);
+}
+  
+ + +

7.10 gDay Serializer

+ +

The argument type of the gday_simpl serializer + implementation is const xml_schema::gday& The + gday class represents a day of the month with + an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 7.6, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gday: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gday ();
+
+    explicit
+    gday (unsigned short day);
+
+    gday (unsigned short day, short zone_hours, short zone_minutes);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const gday&, const gday&);
+
+  bool
+  operator!= (const gday&, const gday&);
+}
+  
+ +

7.11 gMonth Serializer

+ +

The argument type of the gmonth_simpl serializer + implementation is const xml_schema::gmonth&. The + gmonth class represents a month of the year with + an optional time zone. Its interface is presented below. For + more information on the base xml_schema::time_zone + class refer to Section 7.6, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gmonth: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gmonth ();
+
+    explicit
+    gmonth (unsigned short month);
+
+    gmonth (unsigned short month,
+            short zone_hours, short zone_minutes);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+  };
+
+  bool
+  operator== (const gmonth&, const gmonth&);
+
+  bool
+  operator!= (const gmonth&, const gmonth&);
+}
+  
+ +

7.12 gMonthDay Serializer

+ +

The argument type of the gmonth_day_simpl serializer + implementation is const xml_schema::gmonth_day&. + The gmonth_day class represents a day and a month of + the year with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 7.6, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gmonth_day: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gmonth_day ();
+
+    gmonth_day (unsigned short month, unsigned short day);
+
+    gmonth_day (unsigned short month, unsigned short day,
+                short zone_hours, short zone_minutes);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+
+    unsigned short
+    day () const;
+
+    void
+    day (unsigned short);
+  };
+
+  bool
+  operator== (const gmonth_day&, const gmonth_day&);
+
+  bool
+  operator!= (const gmonth_day&, const gmonth_day&);
+}
+  
+ +

7.13 gYear Serializer

+ +

The argument type of the gyear_simpl serializer + implementation is const xml_schema::gyear&. The + gyear class represents a year with an optional + time zone. Its interface is presented below. For more information + on the base xml_schema::time_zone class refer to + Section 7.6, "Time Zone Representation".

+ +
+namespace xml_schema
+{
+  class gyear: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gyear ();
+
+    explicit
+    gyear (int year);
+
+    gyear (int year, short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+  };
+
+  bool
+  operator== (const gyear&, const gyear&);
+
+  bool
+  operator!= (const gyear&, const gyear&);
+}
+  
+ +

7.14 gYearMonth Serializer

+ +

The argument type of the gyear_month_simpl serializer + implementation is const xml_schema::gyear_month&. + The gyear_month class represents a year and a month + with an optional time zone. Its interface is presented below. + For more information on the base xml_schema::time_zone + class refer to Section 7.6, "Time Zone + Representation".

+ +
+namespace xml_schema
+{
+  class gyear_month: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    gyear_month ();
+
+    gyear_month (int year, unsigned short month);
+
+    gyear_month (int year, unsigned short month,
+                 short zone_hours, short zone_minutes);
+
+    int
+    year () const;
+
+    void
+    year (int);
+
+    unsigned short
+    month () const;
+
+    void
+    month (unsigned short);
+  };
+
+  bool
+  operator== (const gyear_month&, const gyear_month&);
+
+  bool
+  operator!= (const gyear_month&, const gyear_month&);
+}
+  
+ + +

7.15 time Serializer

+ +

The argument type of the time_simpl serializer implementation + is const xml_schema::time&. The time class + represents hours, minutes, and seconds with an optional time zone. Its + interface is presented below. For more information on the base + xml_schema::time_zone class refer to Section + 7.6, "Time Zone Representation".

+ +
+namespace xml_schema
+{
+  class time: public time_zone
+  {
+  public:
+    // The default constructor creates an uninitialized object.
+    // Use modifiers to initialize it.
+    //
+    time ();
+
+    time (unsigned short hours, unsigned short minutes, double seconds);
+
+    time (unsigned short hours, unsigned short minutes, double seconds,
+          short zone_hours, short zone_minutes);
+
+    unsigned short
+    hours () const;
+
+    void
+    hours (unsigned short);
+
+    unsigned short
+    minutes () const;
+
+    void
+    minutes (unsigned short);
+
+    double
+    seconds () const;
+
+    void
+    seconds (double);
+  };
+
+  bool
+  operator== (const time&, const time&);
+
+  bool
+  operator!= (const time&, const time&);
+}
+  
+ + + + + +

8 Document Serializer and Error Handling

+ +

In this chapter we will discuss the xml_schema::document_simpl + type, the error handling mechanisms provided by the mapping, as well as + how to reuse a serializer after an error has occurred.

+ +

There are four categories of errors that can result from running + a serializer to produce an XML instance: system, xml, schema, and + application. The system category contains memory allocation and + input/output operation errors. The xml category is for XML serialization + and well-formedness checking errors. Similarly, the schema category is + for XML Schema validation errors. Finally, the application category + is for application logic errors that you may want to propagate + from serializer implementations to the caller of the serializer. +

+ +

The C++/Serializer mapping supports two methods of reporting errors: + using C++ exceptions and with error codes. The method used depends + on whether or not you have configured the XSD/e runtime and + the generated code with C++ exceptions enabled, as described + in Section 6.3, "C++ Exceptions".

+ +

8.1 Document Serializer

+ +

The xml_schema::document_simpl serializer is a root + serializer for the vocabulary. As mentioned in Section + 3.4, "Connecting the Serializer Together", its interface varies + depending on the mapping configuration (Chapter 6, "Mapping + Configuration"). When STL, C++ exceptions, and the iostream library + are enabled, the xml_schema::document_simpl class has the + following interface:

+ +
+namespace xml_schema
+{
+  class serializer_base;
+
+  class writer
+  {
+  public:
+    // The first write function is called to write a '\0'-terminated
+    // string. Its default implementation calls the second versions:
+    // write (s, strlen (s)). These functions use exceptions to
+    // indicate a write failure.
+    //
+    virtual void
+    write (const char* s);
+
+    virtual void
+    write (const char* s, size_t n) = 0;
+
+    virtual void
+    flush () = 0;
+  };
+
+  class document_simpl
+  {
+  public:
+    document_simpl (serializer_base&,
+                    const char* root_element_name);
+
+    document_simpl (serializer_base&,
+                    const char* root_element_namespace,
+                    const char* root_element_name);
+
+    document_simpl (serializer_base&,
+                    const std::string& root_element_name);
+
+    document_simpl (serializer_base&,
+                    const std::string& root_element_namespace,
+                    const std::string& root_element_name);
+
+  public:
+    void
+    add_prefix (const char* prefix, const char* namespace_);
+
+    void
+    add_default_prefix (const char* namespace_);
+
+    void
+    add_schema (const char* namespace_, const char* location);
+
+    void
+    add_no_namespace_schema (const char* location);
+
+    void
+    add_prefix (const std::string& prefix,
+                const std::string& namespace_);
+
+    void
+    add_default_prefix (const std::string& namespace_);
+
+    void
+    add_schema (const std::string& namespace_,
+                const std::string& location);
+
+    void
+    add_no_namespace_schema (const std::string& location);
+
+  public:
+    // Serialization flags.
+    //
+    typedef unsigned short flags;
+
+    static const flags pretty_print;
+
+  public:
+    // Serialize to std::ostream. The std::ios_base::failure
+    // exception is used to report io errors (badbit and failbit)
+    // if C++ exceptions are enabled. Otherwise error codes are
+    // used.
+    //
+    void
+    serialize (std::ostream&, flags = 0);
+
+  public:
+    // Serialize by calling writer::write() and writer::flush() to
+    // output XML.
+    //
+    void
+    serialize (writer&, flags = 0);
+
+    // Serialize by calling the write and flush functions. If the
+    // unbounded write function is not provided, the bounded version
+    // is called: write_bound_func (s, strlen (s)). user_data is
+    // passed as a first argument to these functions. These functions
+    // use exceptions to indicate a write failure.
+    //
+    typedef void (*write_func) (void*, const char*);
+    typedef void (*write_bound_func) (void*, const char*, size_t);
+    typedef void (*flush_func) (void*);
+
+    void
+    serialize (write_bound_func,
+               flush_func,
+               void* user_data,
+               flags = 0);
+
+    void
+    serialize (write_func,
+               write_bound_func,
+               flush_func,
+               void* user_data,
+               flags = 0);
+  public:
+    // Low-level, genx-specific serialization. With this method
+    // it is your responsibility to call genxStartDoc*() and
+    // genxEndDocument().
+    //
+    void
+    serialize (genxWriter);
+  };
+}
+  
+ +

When the use of STL is disabled, the constructors, as well as + the add_prefix() and add_schema() + functions that use std::string in their signatures + are not available. When the use of iostream is disabled, the + serialize() functions that serializes to + std::ostream is not available.

+ +

When C++ exceptions are disabled, the write() and + flush() virtual functions in the writer + interface as well as write_func, + write_bound_func, and flush_func + function pointers use bool return type + for error reporting. These functions should return true + if the operation was successful and false otherwise. + The relevant parts in the writer and + document_simpl interfaces change as follows:

+ +
+namespace xml_schema
+{
+  class serializer_base;
+
+  class writer
+  {
+  public:
+    // The first write function is called to write a '\0'-terminated
+    // string. Its default implementation calls the second versions:
+    // write (s, strlen (s)). These functions return true if the
+    // operation was successful and false otherwise.
+    //
+    // indicate a write failure.
+    //
+    virtual bool
+    write (const char* s);
+
+    virtual bool
+    write (const char* s, size_t n) = 0;
+
+    virtual bool
+    flush () = 0;
+  };
+
+  class document_simpl
+  {
+    ...
+
+    // Serialize by calling the write and flush functions. If the
+    // unbounded write function is not provided, the bounded version
+    // is called: write_bound_func (s, strlen (s)). user_data is
+    // passed as a first argument to these functions. These functions
+    // return true if the operation was successful and false otherwise.
+    //
+    typedef bool (*write_func) (void*, const char*);
+    typedef bool (*write_bound_func) (void*, const char*, size_t);
+    typedef bool (*flush_func) (void*);
+
+    ...
+
+  public:
+    const serializer_error&
+    _error () const;
+  };
+}
+  
+ +

For more information on error handling with C++ exceptions and + error codes see Section 8.2, "Exceptions" + and Section 8.3, "Error Codes" below.

+ +

When support for XML Schema polymorphism is enabled, the + overloaded document_simpl constructors have + additional arguments which control polymorphic serialization. + For more information refer to Section 6.7, + "Support for Polymorphism". +

+ +

The first argument to all overloaded constructors is the + serializer for the type of the root element. The + serializer_base class is the base type for all + serializer skeletons. The second and third arguments to the + document_simpl's constructors are the root element's + name and namespace.

+ +

The add_prefix() and add_default_prefix() + functions allow you to establish custom prefixes for XML + namespaces. If none is provided, and namespaces are used + by your vocabulary, the serializer will automatically + assign namespace prefixes in an implementation-specific + manner. For example:

+ +
+xml_schema::document_simpl doc_s (
+  root_s,
+  "http://www.example.com/example",
+  "root");
+
+doc_s.add_prefix ("ex", "http://www.example.com/example");
+  
+ +

The resulting XML will have the following namespace declaration:

+ +
+<ex:root xmlns:ex="http://www.example.com/example" ...>
+  ...
+</ex:root>
+  
+ +

Similarly, the add_schema() and + add_no_namespace_schema() functions allow you to embed + schema location information for a particular namespace into resulting + XML. The schema location information is placed into the + xsi:schemaLocation and + xsi:noNamespaceSchemaLocation attributes. For example:

+ +
+xml_schema::document_simpl doc_s (
+  root_s,
+  "http://www.example.com/example",
+  "root");
+
+doc_s.add_prefix ("ex", "http://www.example.com/example");
+doc_s.add_schema ("http://www.example.com/example", "example.xsd");
+  
+ +

The resulting XML will have the following namespace declaration:

+ +
+<ex:root
+  xmlns:ex="http://www.example.com/example"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://www.example.com/example example.xsd" ...>
+  ...
+</ex:root>
+  
+ +

8.2 Exceptions

+ +

When C++ exceptions are used for error reporting, the system + errors are mapped to the standard exceptions. The out of memory + condition is indicated by throwing an instance + of std::bad_alloc. The stream operation errors + are reported by throwing an instance of + std::ios_base::failure.

+ +

The xml and schema errors are reported by throwing the + xml_schema::serializer_xml and + xml_schema::serializer_schema + exceptions, respectively. These two exceptions derive from + xml_schema::serializer_exception which, in turn, derives + from std::exception. As a result, you can handle + any error from these two categories by either catching + std::exception, xml_schema::serializer_exception, + or individual exceptions. The further down the hierarchy you go + the more detailed error information is available to you. The + following listing shows the definitions of these exceptions:

+ +
+namespace xml_schema
+{
+  class serializer_exception: public std::exception
+  {
+  public:
+    virtual const char*
+    text () const = 0;
+
+    ...
+  };
+
+  std::ostream&
+  operator<< (std::ostream&, const serializer_exception&);
+
+
+  typedef <implementation-details> serializer_xml_error;
+
+  class serializer_xml: public serializer_exception
+  {
+  public:
+    serializer_xml_error
+    code () const;
+
+    virtual const char*
+    text () const;
+
+    virtual const char*
+    what () const throw ();
+
+    ...
+  };
+
+
+  typedef <implementation-details> serializer_schema_error;
+
+  class serializer_schema: public serializer_exception
+  {
+  public:
+    serializer_schema_error
+    code () const;
+
+    virtual const char*
+    text () const;
+
+    virtual const char*
+    what () const throw ();
+
+    ...
+  };
+}
+  
+ +

The serializer_xml_error and + serializer_schema_error are implementation-specific error + code types. The operator<< defined for the + serializer_exception class simply prints the error + description as returned by the text() function. The + following example shows how we can catch these exceptions:

+ +
+int
+main ()
+{
+  try
+  {
+    // Serialize.
+  }
+  catch (const xml_schema::serializer_exception& e)
+  {
+    cout << "error: " << e.text () << endl;
+    return 1;
+  }
+}
+  
+ +

Finally, for reporting application errors from serializer callbacks, + you can throw any exceptions of your choice. They are propagated + to the caller of the serializer without any alterations.

+ +

8.3 Error Codes

+ +

When C++ exceptions are not available, error codes are used to + report error conditions. Each serializer skeleton and the root + document_simpl serializer have the following member + function for querying the error status:

+ +
+xml_schema::serializer_error
+_error () const;
+  
+ +

To handle all possible error conditions, you will need to obtain + the error status after calls to: the document_simpl's + constructor (it performs memory allocations which may fail), + calls to add_prefix() and add_schema() + functions if any, the call to the root serializer pre() + callback, the call to the serialize() function, and, + finally, the call to the root serializer post() callback. + The definition of xml_schema::serializer_error class + is presented below:

+ +
+namespace xml_schema
+{
+  class sys_error
+  {
+  public:
+    enum value
+    {
+      none,
+      no_memory,
+      open_failed,
+      read_failed,
+      write_failed
+    };
+
+    sys_error (value);
+
+    operator value () const;
+
+    static const char*
+    text (value);
+
+    ...
+  };
+
+  typedef <implementation-details> serializer_xml_error;
+  typedef <implementation-details> serializer_schema_error;
+
+  class serializer_error
+  {
+  public:
+    enum error_type
+    {
+      none,
+      sys,
+      xml,
+      schema,
+      app
+    };
+
+    error_type
+    type () const;
+
+    // Returns true if there is an error so that you can write
+    // if (s.error ()) or if (error e = s.error ()).
+    //
+    typedef void (error::*bool_convertible) ();
+    operator bool_convertible () const;
+
+    // system
+    //
+    sys_error
+    sys_code () const;
+
+    const char*
+    sys_text () const;
+
+    // xml
+    //
+    serializer_xml_error
+    xml_code () const;
+
+    const char*
+    xml_text () const;
+
+    // schema
+    //
+    serializer_schema_error
+    schema_code () const;
+
+    const char*
+    schema_text () const;
+
+    // app
+    //
+    int
+    app_code () const;
+
+    ...
+  };
+}
+  
+ +

The serializer_xml_error and + serializer_schema_error are implementation-specific + error code types. The serializer_error class incorporates + four categories of errors which you can query by calling the + type() function. The following example shows how to + handle error conditions with error codes. It is based on the + person record example presented in Chapter 3, "Serializer + Skeletons".

+ +
+int
+main ()
+{
+  // Construct the serializer.
+  //
+  xml_schema::short_simpl short_s;
+  xml_schema::string_simpl string_s;
+
+  gender_simpl gender_s;
+  person_simpl person_s;
+  people_simpl people_s;
+
+  person_s.serializers (string_s, string_s, gender_s, short_s);
+  people_s.serializers (person_s);
+
+  // Serialize.
+  //
+  using xml_schema::serializer_error;
+  serializer_error e;
+
+  do
+  {
+    xml_schema::document_simpl doc_s (people_s, "people");
+    if (e = doc_s._error ())
+      break;
+
+    people_s.pre ();
+    if (e = people_s._error ())
+      break;
+
+    doc_s.serialize (cout);
+    if (e = doc_s._error ())
+      break;
+
+    people_s.post ();
+    e = people_s._error ();
+
+  } while (false);
+
+  // Handle errors.
+  //
+  if (e)
+  {
+    switch (e.type ())
+    {
+    case serializer_error::sys:
+      {
+        cerr << "system error: " << e.sys_text () << endl;
+        break;
+      }
+    case serializer_error::xml:
+      {
+        cerr << "xml error: " << e.xml_text () << endl;
+        break;
+      }
+    case serializer_error::schema:
+      {
+        cerr << "schema error: " << e.schema_text () << endl;
+        break;
+      }
+    case serializer_error::app:
+      {
+        cerr << "application error: " << e.app_code () << endl;
+        break;
+      }
+    }
+    return 1;
+  }
+}
+  
+ +

The error type for application errors is int with + the value 0 indicated the absence of error. You can + set the application error by calling the _app_error() + function inside a serializer callback. For example, if it was invalid + to have a person younger than 18 in our people catalog, then we + could have implemented this check as follows:

+ +
+class person_simpl: public person_sskel
+{
+public:
+  virtual short
+  age ()
+  {
+    short a = ...;
+
+    if (a < 18)
+      _app_error (1);
+
+    return a;
+  }
+};
+  
+ +

You can also set a system error by calling the _sys_error() + function inside a serializer callback. This function has one argument of + type xml_schema::sys_error which was presented above. + For example:

+ +
+class person_simpl: public person_sskel
+{
+public:
+  virtual const char*
+  first_name ()
+  {
+    char* r = new char[5];
+
+    if (r == 0)
+    {
+      _sys_error (xml_schema::sys_error::no_memory);
+      return 0;
+    }
+
+    strcpy (r, "John");
+    return r;
+  }
+};
+  
+ +

8.4 Reusing Serializers after an Error

+ +

After a successful execution a serializer returns into the initial + state and can be used to serialize another document without any + extra actions. On the other hand, if an error occurred during + serialization and you would like to reuse the serializer to serialize another + document, you need to explicitly reset it into the initial + state as shown in the following code fragment:

+ +
+int
+main ()
+{
+  ...
+
+  xml_schema::document_simpl doc_s (people_s, "people");
+
+  for (size_t i = 0; i < 4; ++i)
+  {
+    try
+    {
+      people_s.pre ();
+      doc_s.serialize (cout);
+      people_s.post ();
+    }
+    catch (const xml_schema::serializer_exception&)
+    {
+      doc_s.reset ();
+    }
+  }
+}
+  
+ +

If you do not need to reuse serializers after an error for example + because your application terminates or you create a new serializer + instance in such situations, then you can avoid generating + serializer reset code by specifying the --suppress-reset + XSD/e compiler option.

+ +

Your individual serializer implementations may also require extra + actions in order to bring them into a usable state after an + error. To accomplish this you can override the _reset() + virtual function as shown below. Notice that when you override the + _reset() function in your implementation, you should + always call the base skeleton version to allow it to reset + its state:

+ +
+class person_simpl: public person_sskel
+{
+public:
+  virtual void
+  pre (person* p)
+  {
+    p_ = p;
+  }
+
+  virtual void
+  post ()
+  {
+    delete p_;
+    p_ = 0;
+  }
+
+  virtual void
+  _reset ()
+  {
+    person_sskel::_reset ();
+    delete p_;
+    p_ = 0;
+  }
+
+  ...
+
+private:
+  person* p_;
+};
+  
+ +

Note also that the _reset() mechanism is used only when + an error has occurred. To make sure that your serializer implementations + arrive at the initial state during successful execution, use the + initialization (pre() and _pre()) and + finalization (post_*() and _post()) + callbacks.

+ + + + + +

Appendix A — Supported XML Schema Constructs

+ +

The Embedded C++/Serializer mapping supports validation of the following + W3C XML Schema constructs in the generated code.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstructNotes
Structure
element
attribute
any
anyAttribute
all
sequence
choice
complex type, empty content
complex type, mixed content
complex type, simple content extension
complex type, simple content restriction
complex type, complex content extension
complex type, complex content restriction
list
Facets
lengthString-based types.
minLengthString-based types.
maxLengthString-based types.
patternString-based types.
enumerationString-based types.
minExclusiveInteger and floating-point types.
minInclusiveInteger and floating-point types.
maxExclusiveInteger and floating-point types.
maxInclusiveInteger and floating-point types.
Datatypes
byte
unsignedByte
short
unsignedShort
int
unsignedInt
long
unsignedLong
integer
nonPositiveInteger
nonNegativeInteger
positiveInteger
negativeInteger
boolean
float
double
decimal
string
normalizedString
token
Name
NMTOKEN
NCName
language
anyURI
IDIdentity constraint is not enforced.
IDREFIdentity constraint is not enforced.
NMTOKENS
IDREFSIdentity constraint is not enforced.
QName
base64Binary
hexBinary
date
dateTime
duration
gDay
gMonth
gMonthDay
gYear
gYearMonth
time
+ +
+
+ + + + diff --git a/doc/cxx/serializer/guide/makefile b/doc/cxx/serializer/guide/makefile new file mode 100644 index 0000000..7502a53 --- /dev/null +++ b/doc/cxx/serializer/guide/makefile @@ -0,0 +1,48 @@ +# file : doc/cxx/serializer/guide/makefile +# author : Boris Kolpackov +# copyright : Copyright (c) 2006-2011 Code Synthesis Tools CC +# license : GNU GPL v2 + exceptions; see accompanying LICENSE file + +include $(dir $(lastword $(MAKEFILE_LIST)))../../../../build/bootstrap.make + +default := $(out_base)/ +dist := $(out_base)/.dist +dist-win := $(out_base)/.dist-win +cleandoc := $(out_base)/.cleandoc + +# Build. +# +$(default): $(out_base)/cxx-serializer-e-guide.ps \ + $(out_base)/cxx-serializer-e-guide.pdf + + +$(out_base)/cxx-serializer-e-guide.ps: $(src_base)/index.xhtml \ + $(src_base)/figure-1.png \ + $(src_base)/guide.html2ps \ + | $(out_base)/. + $(call message,html2ps $<,html2ps -f $(src_base)/guide.html2ps -o $@ $<) + +$(out_base)/cxx-serializer-e-guide.pdf: $(out_base)/cxx-serializer-e-guide.ps | $(out_base)/. + $(call message,ps2pdf $<,ps2pdf14 $< $@) + +# Dist. +# +$(dist): path := $(subst $(src_root)/,,$(src_base)) +$(dist): $(out_base)/cxx-serializer-e-guide.ps $(out_base)/cxx-serializer-e-guide.pdf + $(call install-data,$(src_base)/figure-1.png,$(dist_prefix)/$(path)/figure-1.png) + $(call install-data,$(src_base)/index.xhtml,$(dist_prefix)/$(path)/index.xhtml) + $(call install-data,$(out_base)/cxx-serializer-e-guide.ps,$(dist_prefix)/$(path)/cxx-serializer-e-guide.ps) + $(call install-data,$(out_base)/cxx-serializer-e-guide.pdf,$(dist_prefix)/$(path)/cxx-serializer-e-guide.pdf) + +$(dist-win): $(dist) + + +# Clean. +# +$(cleandoc): + $(call message,rm $$1,rm -f $$1,$(out_base)/cxx-serializer-e-guide.ps) + $(call message,rm $$1,rm -f $$1,$(out_base)/cxx-serializer-e-guide.pdf) + +# How to. +# +$(call include,$(bld_root)/install.make) -- cgit v1.1