Home > Articles > Web Services > XML

Generating XML Documents from Databases

📄 Contents

  1. XML::Generator::DBI Perl Module
  2. Summary
In this article, Mark Riehl and Ilya Sterin discuss an easy way to generate XML from a database result set where a more powerful approach is not needed.
Like this article? We recommend

Like this article? We recommend

One of the most popular uses of XML is as a data storage facility. Because XML is based on a hierarchical data format, it's suitable to store almost any information, and it has the capability to mimic some of the capabilities found in relational database management systems (RDBMSs). However, since XML is stored in a text format, data cannot be retrieved as quickly or stored as efficiently when compared to the binary formats used by modern RDBMSs.

XML is often used to transfer data between disparate systems. A large number of systems today exchange data stored in XML even though they were never originally designed to do so. An example of such a system is an e-commerce business. Sometimes, orders may be collected by one company and the merchandise is shipped by another company. In this type of business arrangement, the companies could use XML to exchange order information. Usually, the order data is stored in an underlying database, so the key for this type of transaction is to convert order data stored in a database into an XML document.

This article discusses how you can use Perl to produce XML documents using a database as your data source. We'll focus on the XML::Generator::DBI.

NOTE

You'll need to install the following Perl modules to test the code examples in this article:

  • XML::Generator::DBI

  • DBI

  • DBD::CSV

XML::Generator::DBI Perl Module

One of the most frequently performed tasks while integrating XML and RDBMS formats is transforming the query results returned by the database engine into XML data (either in memory, or written out in the form of an XML document). The Perl DBI is a database independent interface for querying and inserting data into a large number of databases. It enables you to run SQL queries to extract data from a DBMS and returns this data in a Perl data structure. You can then easily convert the results of an SQL query into XML data by using the Perl XML::DBI::Generator module that was written by Matt Sergeant.

This module enables you to generate Simple API for XML (SAX) events that are created as the result of an SQL query to a RDBMS. Basically, this facilitates the transformation of the results of an SQL RDBMS query directly to XML.

The XML output can easily be customized by setting attributes when you instantiate an XML::DBI::Generator object. After the desired attributes are set, you can make the SQL query, and using a handler module (for example, XML::Handler::YAWriter), you can generate the SQL query results in XML. The module's wide range of supported attributes provides a number of different options. However, if this module still doesn't support something you need to do, you can easily write your own handler and customize the behavior. This demonstrates the power and flexibility of SAX-based XML parsing.

Let's now look at a scenario where XML::Generator::DBI can be put to work. We purposely avoided using a RDBMS in this first example; this scenario demonstrates the utility of the XML::Generator::DBI Perl module without requiring you to install a RDBMS. Depending on the RDBMS that you select, setup can range anywhere from trivial to challenging. This first example uses a standard Comma Separated Value (CSV) file as our flat file database system. DBI has a driver for CSV that can manipulate the file as if it were a real RDBMS. This example only requires installation of the Perl DBI and DBD::CSV modules.

XML::DBI::Generator Perl Module and CSV Example

In this example, we want to develop a Perl program that performs the following steps:

  1. Create a table in the database.

  2. Insert data into the table.

  3. Query the database.

  4. Convert the results of the query into XML.

Sounds like a real task requiring some code writing, right? In reality, this program is a lot shorter than you might think. This example requires less than one-half of a page of source code. This example demonstrates how quickly and easily you can create a real application by taking advantage of existing Perl modules. The Perl modules handle the low-level details, allowing you to focus on other aspects of the application.

XML::DBI::Generator Perl Program

Now, let's take a closer look at the Perl program shown in Listing 1 that performs these tasks. In this example, we'll be using DBI and the DBD::CSV driver to create a database populated with some sample data that queries the data and generates a result set in XML format.

Listing 1—Perl application using the XML::Generator::DBI module and DBI Perl modules. (Filename: Listing 1)

1.  use strict;
2.  use XML::Generator::DBI;
3.  use XML::Handler::YAWriter;
4.  use DBI;
5.  
6.  # Instantiate a new XML::Handler::YAWriter object.
7.  my $ya = XML::Handler::YAWriter->new(AsFile => "-", 
8.          Pretty => {PrettyWhiteNewline => 1,
9.           PrettyWhiteIndent => 1});
10. 
11. # Create a DBI connection.
12. my $dbh = DBI->connect("dbi:CSV:f_dir=./");
13. $dbh->{RaiseError} = 1;
14. 
15. # Create a database table with columns named id and name.
16. $dbh->do("CREATE TABLE USERS (ID INTEGER, NAME CHAR(10))");
17. 
18. # Insert data into the database table.
19. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (1, 'Larry Wall')");
20. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (2, 'Tim Bunce')");
21. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (3, 'Matt Sergeant')");
22. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (4, 'Ilya Sterin')");
23. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (5, 'Robin Berjon')");
24. 
25. # Instantiate a new XML::Generator::DBI object.
26. my $generator = XML::Generator::DBI->new(
27.             Handler => $ya,
28.             dbh => $dbh);
29. 
30. # Execute the enclosed SQL query.
31. $generator->execute("SELECT ID, NAME FROM USERS");
32. 
33. # Remove the USERS table from the database.
34. $dbh->do("DROP TABLE USERS");
35. 
36. # Disconnect from the CSV database.
37. $dbh->disconnect();

1–9—This program starts with the standard use strict pragma. Because we're using the XML::Generator::DBI, XML::Handler::YAWriter, and the DBI Perl modules, we need to include their respective use pragmas to load the modules. We're going to use the XML::Handler::YAWriter Perl module to serve as our event handler.

1.  use strict;
2.  use XML::Generator::DBI;
3.  use XML::Handler::YAWriter;
4.  use DBI;
5.  
6.  # Instantiate a new XML::Handler::YAWriter object.
7.  my $ya = XML::Handler::YAWriter->new(AsFile => "-", 
8.  				   Pretty => {PrettyWhiteNewline => 1,
9.  						PrettyWhiteIndent => 1});

11–13—In this section, we call the DBI module's connect() function to connect a DBI object. The RaiseError attribute is then set to true; this will cause any DBI errors to terminate the program with an error message.

11. # Create a DBI connection
12. my $dbh = DBI->connect("dbi:CSV:f_dir=./");
13. $dbh->{RaiseError} = 1;

15–16—We call the DBI do() function, which allows us to immediately execute a query that does not require us to return a result set (for example, a CREATE or INSERT SQL statement). In this case, we execute the CREATE TABLE SQL statement that will create a new table named USERS with two fields, ID and NAME. Because we're using the DBD::CSV DBI driver case, this function will create a new file named USERS, which will act as our table.

15. # Create a database table with columns named id and name.
16. $dbh->do("CREATE TABLE USERS (ID INTEGER, NAME CHAR(10))");

18–23—Now we insert some sample data into our newly created USERS table.

18. # Insert data into the database table.
19. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (1, 'Larry Wall')");
20. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (2, 'Tim Bunce')");
21. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (3, 'Matt Sergeant')");
22. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (4, 'Ilya Sterin')");
23. $dbh->do("INSERT INTO USERS (ID, NAME) VALUES (5, 'Robin Berjon')");

It just happens that I listed some of the major contributors in the Perl community. The contents of the database are show in Table 6.2.

Table 6.2—Contents of the database table.

ID

Name

1

Larry Wall

2

Tim Bunce

3

Matt Sergeant

4

Ilya Sterin

5

Robin Berjon


25–28—Instantiate a XML::Generator::DBI object, setting its Handler and dbh attributes. Here we set XML::Handler::YAWriter as the SAX event handler that will receive events generated by the XML::Generator::DBI Perl module. In addition, we set the DBI database handle object ($dbh) to dbh. This is the database handle that the XML::Generator::DBI Perl module uses to execute database queries.

25. # Instantiate a new XML::Generator::DBI object.
26. my $generator = XML::Generator::DBI->new(
27.             Handler => $ya,
28.             dbh => $dbh);

30–31—Here we call the XML::Generator::DBI execute() method, which actually executes our query and starts the transformation process from a result set to XML. Because XML::Handler::YAWriter's AsFile attribute was set to '-' in the XML::Handler::YAWriter constructor, the generated XML will be printed to STDOUT. If you need to generate an XML document instead of having it scroll by on STDOUT, supply an output filename to the XML::Handler::YAWriter constructor instead of the '-'.

30. # Execute the enclosed SQL query.
31. $generator->execute("SELECT ID, NAME FROM USERS");

33–37—After making our queries and generating, we can now delete our USERS table and disconnect from the database. We execute the DROP TABLE function and then call the disconnect() function on the database handle.

33. # Remove the USERS table from the database.
34. $dbh->do("DROP TABLE USERS");
35. 
36. # Disconnect from the CSV database
37. $dbh->disconnect();

The output of our XML::Generator::DBI Perl program is shown in Listing 2. As you can see, each <row> element in the XML document directly maps to a row from the database table. Note that the row elements and the root element in the generated XML document can be changed by using attributes from the XML::Generator::DBI module constructor.

Listing 2—Output of the XML::Generator::DBI Perl program. (Filename: Listing 2)

<?xml version="1.0" encoding="UTF-8"?>
<database>
 <select
   query="SELECT ID, NAME FROM USERS">
  <row>
   <ID>1</ID>
   <NAME>Larry Wall</NAME>
  </row>
  <row>
   <ID>2</ID>
   <NAME>Tim Bunce</NAME>
  </row>
  <row>
   <ID>3</ID>
   <NAME>Matt Sergeant</NAME>
  </row>
  <row>
   <ID>4</ID>
   <NAME>Robin Berjon</NAME>
  </row>
  <row>
   <ID>5</ID>
   <NAME>Ilya Sterin</NAME>
  </row>
 </select>
</database>

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