Pages

Friday, June 29, 2012

Resolve namespaces in your XSL Stylesheets

If you're using XSL to transform or format your XML, it's important that you know how to handle XML Namespaces in your applications. You might find that your templates are producing unexpected results.

Listing A: XML bound to a namespace
<?xml version="1.0"?>
<root xmlns="http://www.somecompany.com/schema">
    <child></child>
</root>

The XSL Stylesheet below matches the root of the XML document and applies templates for elements in the order they occur. The second template matches the root element and outputs text inicating the element has been matched. When you process the XML using this stylesheet, there's no output.

Listing B: XSL Stylesheet
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
       <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="root">
       <xsl:text>xsl:template match="root"</xsl:text>
    </xsl:template>
</xsl:stylesheet>

When you process the stylesheet against the XML, the output is shown below.

Listing B output using Saxon 6.5.3:
<?xml version="1.0" encoding="utf-8"?>

Listing B output using Xalan 2.6.0:
<?xml version="1.0" encoding="UTF-8"?>

In a more general case, you may find that elements or attributes aren't being matched as you expected. Your stylesheet needs to be aware of any namespaces that might exist in the XML. The stylesheet below illustrates how an XSL processor matches an element that's bound to a namespace in the source XML document.

Listing C: XSL Stylesheet with namespace support

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:result="http://www.somecompany.com/schema">
    <xsl:template match="/">
       <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="root">
       <xsl:text>xsl:template match="root"</xsl:text>
    </xsl:template>

    <xsl:template match="result:root">
       <xsl:text>xsl:template match="result:root"</xsl:text>
    </xsl:template>
</xsl:stylesheet>

Listing C output using Saxon 6.5.3:
<?xml version="1.0" encoding="utf-8"?>xsl:template match="result:root"

Listing C output using Xalan 2.6.0:
<?xml version="1.0" encoding="UTF-8"?>
xsl:template match="result:root"



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.