XML and Java


This page will walk you through the basics of styling and transforming XML


XML is converted into other things, and formatted, using XSL (eXtensible Stylesheet Language). This has several parts, two of which are XSLT (XSL Transformations) and XPath. XPath is used to divide a XML document up into sections and navigate around it. It is a bit like using "/" and "../" in DOS or UNIX directories (root and down-one-directory respectively). You can find a tutorial on XPath here, from W3Schools. The following code uses the XPath "//" (all elements like this in the XML), "@" (attribute) and "/" (root of the document) markers.


XSLT (XSL Transformations) is used to turn XML into something else. Here's an example that uses our polygon to produce some HTML:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method='html' version='1.0' encoding='UTF-8' indent='yes'/>
<xsl:template match="/">
<html>
<body>
<h2>Polygons</h2>
<p>
<xsl:for-each select="map/polygon">
<P>
<xsl:value-of select="@id"/> :
<xsl:value-of select="points"/>
</P>
</xsl:for-each>
</p> </body>
</html>
</xsl:template>
</xsl:stylesheet>

Again, here's the XML file linked to the same XSD and the above XSL file. You should be able to open it and see it interpreted by a web browser.

The XSL file is, again, XML, but contains "template" areas which include other types of information - in this case HTML. In addition, there are XSL commands that do stuff like selecting different elements from the XML based on XPaths, and drop them into the template. Here we just display the polygon id attribute and points. XSL includes quite sophisticated commands for looping through XML (see for-each, above), sorting XML elements and doing basic comparisons. You can find a good W3Schools tutorial here.


You should just be able to use different XSL files to convert your XML to different things. Here, for example, is an XSL file to convert the XML / XSD into SVG - a vector drawing of a polygon you should be able to see in a web browser - see the same XML file here but now with the XSL referenced.

You can find a more fully worked example converting GML to XML and SVG in: Maria, S. and Tsoulos, L (2003) 'A holistic Approach of Map Composition Utilizing XML' Proceedings of SVG Open 2003 Vancouver, Canada - July 13-18, 2003.


The final trick is to read the XML into Java as an object: that's next.