Home > Articles > Web Services > XML

Mapping between XML and Relational Data

This chapter explores the various methods for mapping between XML and relational data models. It focuses on the underlying fundamentals: goals and requirements for mapping between XML and relational data; issues that arise when mapping, such as handling of datatypes and order; and when a particular technique can or cannot support update operations.
This chapter is from the book

XQuery operates on XML documents—or to be more precise, on instances of an XML data model. Often we assume that these XML documents exist in files or as data in network messages. But in another very common scenario, documents are generated on demand by being translated or created from a different data representation. Relational databases are probably the most important of these different sources of data for XML applications.

This chapter explores the various methods for mapping between XML and relational data models. As of this writing, many relational database vendors have announced various kinds of support for XML, ranging from the ability to transmit results as XML to built-in implementations of XQuery or SQL/XML. In addition, many middleware vendors also provide support for mapping between XML and relational data. In this chapter we do not attempt to cover the specific vendor solutions, since they are in considerable flux. Instead, we focus on the underlying fundamentals: goals and requirements for mapping between XML and relational data; issues that arise when mapping, such as handling of datatypes and order; and when a particular technique can or cannot support update operations. We generally present these concepts from the perspective of a middle-tier solution that builds on top of a relational database. The same concepts are often also valid for implementations integrated within a relational database, but that particular perspective is covered in more detail in Chapter 7, “Integrating XQuery and Relational Database Systems.”

We begin with some background, establishing the processing model that we assume and distinguishing different kinds of applications and data sources insofar as they affect mapping. Then we introduce the main representational dichotomy: storage of XML data as XML strings (called “LOB representation”) or as individual fields or data items (“composed representation”). The largest part of the chapter delves into the common techniques for composed representations and their implications for supporting different application types. We take a special look at shredding, which is the name for the technique of extracting individual data items from an XML document in such a way that it can be recomposed. Finally, we cover the implementation principles for both LOB and composed representations in just enough detail to suggest the strengths and weaknesses of various approaches.

Our goal is to provide enough information so that readers can gauge their requirements, identify potential pitfalls, and stack these up against the various approaches, whether employed by some commercial software package, custom-built, or a combination of the two.

Framing the Problem

In theory, we could discuss the mapping between XML and relational data without reference to the applications that will use such a mapping or how those applications might be implemented. However, these factors have implications for the type of mapping chosen—one may want or be constrained to choose a different mapping technique based on the actual requirements of a particular application. In particular, we consider XQuery as one particular type of application, one that places certain requirements on how to map between XML and relational data. We also consider other types of applications that have fewer or additional requirements.

Processing Models

We will begin by discussing at a high level the processing models that might be used to implement an XML application on top of a relational database. One straightforward processing model layers an XML application on top of an SQL database. In this case, the SQL database itself remains unchanged, and the XML application is implemented via some combination of SQL statements and additional XML-focused processing. Figure 6.1 shows this processing model schematically.

06fig01.gifFigure 6.1. Layered Processing Model for XML Applications

There are several ways to divide the boxes in Figure 6.1:

  • In a completely custom application, the XML Processor functionality might be embedded within the end application, as a library or as custom-written code.

  • With a middle-tier (also known as middleware) approach, the XML Processor is the middleware component and sits between an end application and the relational database, providing a virtual XML view of data stored in the relational database.

  • Part or all of the XML Processor could be implemented as user-defined functions or stored procedures within the database, rather than on a separate tier.

The main alternative to a layered approach is one in which the relational database is extended to provide native XML functionality. In this case, the architecture may still somewhat resemble that shown in Figure 6.1 (except with the XML processor embedded in and accessed from within the overall relational architecture), or we may use an entirely different architecture, in which the XML and relational functionality are mingled together. These alternatives are discussed in Chapter 7.

In this chapter, we generally assume the middle-tier version of the model shown in Figure 6.1. This model is sufficient to cover most issues relating to mapping between XML and relational data; we intend to highlight areas where the choice of a processing model affects the mapping. Issues that arise particularly in a native implementation are discussed in Chapter 7.

Application Types

We characterize types of applications by what basic sorts of operations they have to perform on XML data: extract, transform, and so forth. Significant variation may exist within each application type, based on the particular languages (XQuery, XPath, etc.) used and especially on the richness of the set of specific available operations.

Emitting XML Documents

The most basic application type simply returns an XML document or documents. In this case the relational database is merely acting as a repository for some set of XML documents. The emitted XML document might be used directly by some application, or it might be further processed. For example, the document might be further processed with XSL to transform it for display in a web portal.

Selecting and Emitting XML Fragments

The application type that selects and returns XML fragments is characterized by the XPath language, which returns nodes from within an XML document that match specified conditions. The key requirements are the ability to “reach into” the document to access individual elements, attributes, and their values, both in order to evaluate predicate conditions and to extract the node contents.

A trivial way to implement this application type would be to emit all XML documents (using the application type above), and then in a post-processing step, evaluate the conditions and output only the requested portion of the document or documents. However, this would generally be inefficient, since it could require emitting all the XML documents in order to ultimately retrieve only one or a few documents or document fragments. Thus our main goal for this type of application is to find a way to push the selection and extraction criteria into the database, using the database to perform these operations for us.

This is a common theme throughout this chapter: Whenever possible we want to make the relational database engine perform the kind of work it is good at, rather than repeating this work externally.

Querying or Transforming XML Documents

Querying and transforming are often considered to be different operations, but in terms of the requirements they place on mapping between XML and relational data, they are quite similar. XQuery is the most general example of this kind of application. As we have seen, XQuery has very powerful ways to navigate, select, combine, transform, sort, and aggregate XML data. The output of a query in XQuery may have no structural resemblance to the XML source: elements can be renamed and rearranged, and the data can be transformed by functions. An XQuery query may combine data from multiple XML input documents to create a single output.

XQuery is the most obvious example of a query-and-transform language, but it is not the only one. XSL also performs querying and transformation. And some applications may use their own query or transform definitions; this may especially be appropriate if the needs of the application are much simpler than full XQuery and a general-purpose XQuery implementation is not available. In all cases, the defining characteristic of applications in this class is the ability to both select and combine individual pieces of the XML input in complex ways, creating new XML structures that may not have existed in the input.

As for the “select and extract” application type, it is possible to implement XQuery by first emitting entire XML documents and then post-processing them with a generic XQuery processor. (And similarly for any other query or transform language.) But the more interesting approach is again to push as much of the XQuery processing into the database as possible, in essence translating from XQuery to SQL or an extended language such as SQL/XML.

Updating XML Documents

All of the above application types are read-only: The application processes an XML document and transmits the result of that processing to some other client application. There are fundamental changes when the application must also update the XML document in place.

The most significant new requirement that arises with update is the ability to correctly identify individual nodes within XML documents. For example, if the application needs to change the value of an attribute from owner='sam' to owner='bob', it is not sufficient to find some attribute owner whose value is sam and change the value to bob; it must be the specific attribute referenced by the client. In order to implement this requirement, the client application must have some way to name which node it wishes to modify. There are three general approaches:

  1. The client always provides a new value for the entire document (in which case the problem goes away).

  2. The client must use some form of addressing (e.g., XPath or the tumbler notation of XPointer) to uniquely identify nodes to change.

  3. The communication between the client and the XML management system must be an API that directly provides handles on nodes (e.g., WebDAV or DOM).

The addressing approach tends to increase complexity in the client (which has to generate the addresses), but it still enables the communication channel between the client and the database to consist of serialized XML, which can be easier to implement than a rich API, particularly in a loosely coupled environment. When either the addressing or API approaches are used, update requires the ability to translate either an address or node handle into a location or locations in the database.

Another issue that arises with update is the addition of transactions and locking to the picture, and the need to coordinate these with the underlying SQL engine. Some of the issues involved are addressed in Chapter 7.

Unlike the previous application types, the actual update operations on XML documents must finally be implemented entirely within the database, either directly by the database vendor, or by translation of the update operations to SQL—post-processing cannot help here. The middle tier is used differently in this case: It translates a set of updates against an XML document into a set of update operations on the relational database. The translation process can be quite complex: for example, computing the difference between an updated XML document and its previous version to generate a list of SQL updates, or batching a set of changes into a single update.

Within the class of applications that update XML documents, there is one additional distinction that is very important: Does the application require the ability to change the XML schema of the document? Changing the schema of the document (or equivalent scenarios, such as changing the structure of a document that either has no schema or has a schema that uses the xs:any construct) can greatly increase the complexity of mapping techniques, and rules out some of them altogether.

Sources of XML Data

The other major dimension we must consider is the source of XML data that our applications wish to process.

Relational Sources

In some cases, the original data is actually relational: data stored in tables and columns of the relational database, and generally created and maintained by some relational application. In this situation, we assume that our XML application needs to access this data as if it were XML. We call this general model a virtual XML view of relational data.

XML Sources

XML documents may be the original input data. They might be manually created in an XML editor or created by an XML-based application; for example, they might be received from a B2B (Business-to-Business) application. The originating application might also operate directly on the XML stored within a relational database; for example, an XML editor might store the documents that it manages in a relational database. In this case, we have options to consider regarding how to store the XML within the relational database.

The category of XML sources includes several important subcategories: XML may be structured, semi-structured, or marked-up text, and the XML may either have a given schema (or DTD), variable schemas, or no schema.

Terms like structured and semi-structured have different definitions in the literature; in this chapter, semi-structured XML may have variant substructure (corresponding to the use of union types, xs:choice, or repeating groups), while structured XML does not. As a rule of thumb, it is possible to navigate a structured XML document without examining the document content (e.g., the first child element of the second child element of the root will always be an address element). Marked-up text uses mixed element content and has the additional challenge that logical units of text (such as sentences) may span multiple elements.

Many applications manipulate documents with only a single given schema or DTD. Other applications require the ability to interchangeably manipulate documents with different schemas or change the schema of a given document from time to time as the document is updated. In general, structured or semi-structured XML with a given schema is the easiest to handle, and the other alternatives all significantly increase the complexity of mapping between XML and relational data.

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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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