04
Mon, Nov
5 New Articles

Practical SQL: DB2 at Home, Part 5, Building Tables with XML

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

XML is great for hierarchical data, but sometimes you still need a plain old table, and this article will show you how to build one.

 

Last time, we took a little segue into creating XML from relational data. Now it's time to return to the other direction, making relational tables from XML data. XML can easily support a complex nested relationship of data with both optional and repeating elements, but that doesn't always translate very well to the relational world in which the data is presented as nice tables of rows and columns. In this article, I'll introduce you to the techniques you can use to turn hierarchies into grids.

 

XML Versus RelationalA Story of Structure

The real thing I've been trying to do in all of these articles is to compare how data is stored in XML as opposed to our more traditional relational data approach, and how to exploit the differences by building on the similarities. The subject of this article is the XMLTable function, which in a lot of ways really defines how these two data storage techniques equate to one another.

 

Let's start by taking a look at a standard XML structure. Like all the data in these articles, the data comes from the DB2 appliance that we installed way back at the beginning of the series. You could certainly create your own, but it's nice to have common ground to start from. In this case, the common ground is a purchase order, the XML for which looks like this:

 

<PurchaseOrder

PoNum="5003"

OrderDate="2005-02-28"

Status="UnShipped">

<item>

   <partid>100-100-01</partid>

   <name>Snow Shovel, Basic 22 inch</name>

   <quantity>1</quantity>

   <price>9.99</price>

</item>

</PurchaseOrder>

 

This data resides in a column named PORDER in the table PURCHASEORDER. Yes, I know it's not a traditional 10-character file name, but SQL support on the IBM i allows you to easily get around the constraints for both file and field name. Of course, that means that sometimes people go crazy and create fields like ThirdQuarterInvoiceSubtotalForTemporaryTaxCalculations, but that's a different issue. Anyway, the files and fields are already defined in the appliance, and they're fine. So let's take a look at the data. We see that the highest-level tag is PurchaseOrder, which has several attributes: PoNum, OrderDate, and Status. Unlike relational data, where each element has its own column, or flat files where data is in specific locations, the data in an XML stream can come from anywhere within the document, subject to the syntactical rules of XML, which primarily revolve around surrounding data with tags. The attributes are a little different in that they are simply the keyword and the data joined by an equals sign (=), but the basic concept still applies: the name of the data is provided along with the data itself.

 

Then it can get very interesting. In this case, nested within that is an element named item, which we'll return to later. Just think about it for a moment, though; there could easily be zero, one, or a hundred item tags. That's where the straight one-to-one correspondence between an XML document and a single relational table beak down. I'll talk a little more about multiple instance tags before the article ends, but for now let's concentrate on the attributes and see just how we can express those attributes as a table.

 

Using the XMLTable Function

 

050615PlutaFigure1

Figure 1: The XMLTable function extracts attributes and elements and converts them to relational columns.

 

This one figure is jam-packed with information that may not be entirely intuitive at first glance. First, the select statement at the top tells you that we're going to be selecting some columns from the table purchaseorder, but that the columns will come from something we will define later and name xt (which stands for XML table). We're going to show all the columns from xt. The comma then segues into the actual XMLTable definition, which does quite a bit of work even in this simple example. The first parameter defines the path to the document, which starts first with a value preceded by a dollar sign. That value, $po, says that very soon you're going to define "po" as something that contains XML, and sure enough that happens in the next clause: passing porder as "po". That phrase says find the relational field porder; it will have XML in it and the top-level element will be named PurchaseOrder. Note that if the XML doesn't start that way, you won't get any rows.

 

The next clause starts with the keyword columns, which is appropriate, since it defines the columns being extracted from the XML. The first one is named OrderDate, and it comes from the attribute also named OrderDate. Similarly, the column Status comes from the tag Status. These column names do not have to match the tag names, but the tag name (the one following the path keyword) must match the tag in the XML. Also note that in this case, since OrderDate and Status are attributes and not elements, the attribute name is preceded by @. I still don't understand that, but it seems to be pretty standard through all the XML/SQL syntax: attribute names are preceded by @.

 

Done correctly, the XML will generate a nice table of data.

 

050615PlutaFigure2

Figure 2: This is the result of the XMLTable function in Figure 1.

 

This is nice, but it has one shortcoming; it shows only XML data. The result doesn't include any non-XML elements from the record. Our simple table contains, in addition to the XML field named PORDER, a number of traditional relational data fields. One of those is the POID field, which holds the PO number. This field is a duplicate of the PoNum attribute, but it will serve our purpose here of showing just how easy it is to combine relational data with XML elements.

 

050615PlutaFigure3

Figure 3: The XMLElement function embeds relational data within an XML element.

 

Here's a simple change that includes the POID field from the original record. You can see the statement is hardly changed, and it now includes a column from the relational table, as shown in the next figure.

 

050615PlutaFigure4

Figure 4: Adding the POID field in the statements yields the results you might expect.

 

Astute eyes might notice that I also changed the definition of the extracted OrderDate data. You can specify whatever type you like and, as long as the data in the element can be converted to the selected type, XML will do the conversion for you. You need to be careful with this as you would with any automatic conversion; if the data in the tag is bad, the selection will fail miserably.

 

That's it for this article. It really only scratches the surface of XMLTable. Subsequent articles will cover everything from handling multiple lines to using this syntax within a view: it can be very handy for selecting and sorting data from large XML documents. I hope this article convinces you to stay tuned for the upcoming ones!

 

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: