Home > Articles > Web Services > XML

  • Print
  • + Share This
This chapter is from the book

Composition Techniques: Examples

In this section, we consider examples of composition techniques that illustrate the available variety. We divide composition techniques into three fundamental camps: default mappings, extended SQL, and annotated schemas. We illustrate each camp with a specific example—but it should be emphasized that these are just three current examples from a much wider selection, offered by commercial vendors, academic research and freeware.

Default Mapping

In the simplest kind of composition technique, a default mapping,1 the structure of the database is exposed directly, as a fixed form of XML document. This is an implicit composition technique, in which the user has little or no control over the generated XML. Listing 6.7 shows an example of a default mapping.

Listing 6.7 An Example of a Default Mapping from a Table to XML

table customer
name           acctnum     home

Albert Ng      012ab3f     123 Main St.,  Anytown OH 99999
Francis Smith  032cf5d     42 1/2 Seneca, Whositsville, NH 88888

    <name>Albert Ng</name>
    <home>123 Main St.,  Anytown OH 99999</home>
     <name>Francis Smith</name>
     <home>42 1/2 Seneca, Whositsville, NH 88888</home>

In a default mapping, the names of the tables and columns become (with escaping of reserved characters) the names of elements and/or attributes. These elements and attributes are arranged in a simple structure—usually some form of the three-level hierarchy you see here, or a simple variation that uses attributes instead of elements for column values. Datatypes follow some fixed conversion (e.g., SQL VARCHAR to XML String), and null values in the database either become missing elements or elements with missing values.

One advantage of default mapping is that it supports update very easily: Operations to update element values and add or delete elements have a very direct translation into update operations on the underlying database. However, default mapping does not by itself support many applications, since applications often need XML data in certain specific formats that don't happen to correspond to default mappings from the database. But if a default mapping is combined with a general-purpose query or transformation language such as XQuery, then XQuery may be used to “reformat” the implicitly mapped XML document into the desired XML form. Listing 6.8 illustrates a simple example of using XQuery to transform the document from Listing 6.7. This is a very simple example; a more realistic example would probably involve combining data from multiple tables, and so forth.

The combination of default mapping with XQuery is quite powerful in that it re-uses the same transformation capabilities that are supported in XQuery already. It is also generally efficient when the application needs to select from, query, or transform the resulting XML document, which is accomplished by composing the two operations (one query to generate the XML document, the other to select from or transform it). Since XQuery is defined to support query composition, a general XQuery implementation will be able to support this scenario.

Listing 6.8 Using XQuery to Transform a Default-Mapped XML Document

<ActiveCustomers xmlns="http://www.example.com/custlist"> {
   for $i in doc("customer")/CustomerSet/Customer
   let $firstname := substring-before($i/name, " ")
       $lastname := substring-after($i/name, " ")
     <customer acct="{$i/acctnum}">
        <name type="full">

<ActiveCustomers xmlns="http://www.example.com/custlist">
  <customer acct="012ab3f">
    <name type="full">
  <customer acct="032cf5d">
    <name type="full">

One thing to keep in mind is that the advantage of default mapping with respect to update applications is lost when combining default mapping and XQuery. While it is easy to update the directly mapped document itself, it is not usually possible to update an XML document that is the result of a query or transformation, since it suffers from the same “update through views” problem discussed in the previous section.

Extended SQL

Default mapping plus XQuery is one way to create a complex XML structure from relational data. Another is to add the capability to process and generate XML to SQL. An extended SQL language could be directly implemented by a database vendor, or it could be implemented in a layer on top of the database.

This is the approach taken with SQL/XML, which, as of this writing, is in draft form before ISO as an extension to the SQL query language [SQLXML]. SQL/XML could evolve to become a full solution to emitting, querying, transforming, and even updating XML in its own right. We cannot fully cover SQL/XML here, but we can summarize the major points with respect to mapping between XML and relational data.

How does SQL/XML generate XML? SQL/XML consists of a definition of a native XML datatype, as well as definitions of implicit and explicit ways of generating XML from relational data. The native XML datatype allows XML to be manipulated by the SQL query language, which means that XML documents can be treated as relational values (values of columns or procedure parameters, etc.). The language is intended to support both composed and LOB implementations of the native XML datatype.

SQL/XML also defines an implicit default mapping from relational data to XML. The standard defines how SQL identifiers are to be escaped to create legal XML identifiers and vice versa, as well as extensive conversion rules for standard SQL datatypes. The mapping can be applied to individual values, tables, and entire catalogs. Within SQL/XML, the default mapping is used to define the manner in which SQL datatypes are translated to XML when they appear in XML-generating operators.

Finally, SQL/XML defines a set of XML-generating operators that can be used in an SQL expression: XMLELEMENT, XMLFOREST, and XMLGEN. Each of these allows the creation of an XML element (or fixed sequence of elements) with substitution of values from relational data. For example, the XMLELEMENT operator creates an XML element with content mapped from its arguments:

SELECT e.id,
                 XMLATTRIBUTES ( e.name AS "name" ),
                 e.dept ) AS "result"
FROM employees e
WHERE ... ;

This SQL statement generates a table that has two columns, one containing e.id, one containing an XML element Emp, with the indicated contents supplied by values from the employee table. The default mapping rules are used to determine how the data values are translated to XML and how the nested elements are named.

Interestingly, these generator functions lack features that directly support the generation of hierarchy through hierarchical joins. Although they allow you to create XML hierarchy, the hierarchy is all fixed and is populated directly from a relational set of values. Instead, the effect of generation of hierarchy through joins is piggybacked on existing object-relational features of SQL, in particular by applying the direct-mapping rules to nested-relational structures, as shown in Listing 6.9:

Listing 6.9 Generating Hierarchical Structure with Object-Relational Features of SQL/XML

                         select e.empno, e.ename
                         from emp e
                         where e.deptno = d.deptno) 
                   AS emplist)))
       AS deptxml
FROM dept d
WHERE d.deptno = 100;


SQL/XML does provide a function, XMLAGG, which directly supports generation of structure through grouping. It is used in collaboration with the SQL GROUP BY operation as in the example shown in Listing 6.10:

Listing 6.10 Generating Hierarchical Structure through Grouping in SQL/XML

          ( NAME "department"
            XMLELEMENT ( NAME "name" e.dept )
            XMLELEMENT ( NAME "employees"
                         XMLAGG ( 
                           XMLELEMENT ( NAME "emp", e.lname )
          ) AS "dept_list"
FROM employees e
GROUP BY e.dept

The XMLAGG function acts like an aggregation operation, generating a list of XML content (in this case a single nested element): one item for each row in the group. The output of the query of Listing 6.10 might look like the example of Listing 6.11:

Listing 6.11 An Example XMLAGG Result

  <name>Computer Science</name>

Extended SQL composition techniques are well-suited for supporting selection and transformation over XML documents. They usually cannot support update applications, unless the SQL expressions are very limited.

Annotated XML Template

Another way to express the construction of XML from relational data is to supply an XML template that is “decorated” with expressions that indicate how to compute corresponding XML. The template could be in the form of the XML document itself, or it could be an annotated DTD or schema. To illustrate this mapping technique, we use the Annotated XSD Schema language defined by Microsoft in Microsoft SQLXML 3.0 [SQLXML-MS]

To begin with, in MS SQLXML a completely unannotated schema has a default interpretation: Every complex element is presumed to correspond to a table (whose name is the same as the name of the element), and every simple-valued element or attribute is presumed to correspond to a column of that table (with the same name). Annotations are required to override this assumption, and to specify the relationships between nested complex elements.

Listing 6.12 An Annotated XML Schema

<xs:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  <xs:element name="Customer" type="CustomerType"
  <xs:complexType name="CustomerType">
        <xs:element name="Order" maxOccurs="unbounded"
                parent="Customers"  parent-key="CustomerID"
                child="Orders"      child-key="CustomerID"/>
              <xs:attribute name="OrderID" type="xs:integer"
              <xs:attribute name="Amount" type="xs:integer"/>
     <xs:attribute name="CustomerID"  type="xs:string" /> 
     <xs:attribute name="ContactName" type="xs:string" 

Listing 6.12 shows an example, slightly modified from the Microsoft documentation. In this example, the outermost element, Customer, is populated from a table named Customers (indicated by the sql:relation annotation). Similarly, the nested element Order is populated from the table named Orders. The relationship between them is expressed by the sql:relationship annotation, which tells us that the Customers and Orders are joined through the indicated values.2 Multi-attribute joins are indicated by specifying the appropriate attribute names, in order, in the parent-key and child-key fields. The various simple fields (all of which are attributes in this example) either are mapped implicitly from table columns (e.g., CustomerID), or indicate, with the sql:field annotation, the name of the column from which they are derived (e.g., ContactName from Name).

Note that there are no SQL expressions in this technique. Instead, only names of existing tables and columns are allowed. A very simple variation on this mapping technique would be to allow the sql:relation annotation to contain an arbitrary SQL statement, or the sql:field annotation to contain an SQL expression. This would make it possible to generate more flexible XML documents from a given relational database.

But the restriction to table names and columns has a very powerful advantage: It enables the use of this mapping “in reverse,” to support both update operations and shredding of XML documents. If arbitrary expressions were allowed, it would not be possible to support either update or shredding with the same annotated schema. The same trade-off exists in other composition techniques, which either likewise do not allow arbitrary expressions, or in some cases, come in two varieties, where the user chooses which. For example, Microsoft SQLXML handles this by supporting two mapping techniques: annotated XSD to support update and shredding, and an extended SQL notation (the FOR XML clause) for arbitrarily computed XML.

We note below a few more interesting features of the annotated XSD before moving on to our next category:

  • The example in Listing 6.12 showed a generation of hierarchy through joins with a single join between a parent table, Customers, and a child table, Orders. You can also express a parent-child relationship that requires a chain of joins. For example if we wanted XML that contained information about customers and the products they had purchased (but not specifically about their individual orders), that might require a join from Customers to Orders to Products to generate the child elements. This is accomplished by inserting multiple sql:relationship annotations, in order, one for each required join.

  • While the XSD annotation does not permit general conditional expressions, it does allow one limited form of condition. Annotations sql:limit-field and sql:limit-value can be added to any element or attribute that specifies the sql:relation annotation, to indicate that only those rows of the relation that satisfy limit-field=limit-value are to be used. This is useful for selecting rows of a certain type; for instance, in the example shown in Listing 6.13, it selects billing addresses from a generic address table.

    Listing 6.13 Generating XML Elements in Certain Conditions in MS SQLXML

    <xs:element name="BillTo" 
             parent="Customers" parent-key="CustomerID"
             child="Addresses"  child-key="CustomerID" />
  • If the XML Schema contains xs:any, this can be annotated to indicate an “overflow” column where any extra data encountered during shredding will be stored (in string XML form). The system won't do anything with the information in this field, but it will at least be reproducible when the document is recomposed.

The chain of joins and limit-field features are examples of carefully pushing the limits of expressiveness while still maintaining the ability to update.

Additional Mapping Languages

The previous examples added extensions either to SQL or to existing XML standards to bridge the gap between XML and relational data. Another alternative is to express composition in a new, different, language, whose entire goal is to take relational data as input and generate XML data as output, or vice versa. This approach was initially quite popular, but it has waned because it adds an extra level of complexity—a new language to learn—over the other approaches, without adding much in the way of convenience or expressive power.

Additional languages are still in use by some vendors. They may also be used as an internal compiled form for one of the other mechanisms.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020