register
other register

Thursday, July 17, 2008

Dealing with namespace in XSLT

For more general knowledge about namespace, please refer to XML Namespaces and How They Affect XPath and XSLT


If you have an vanilla xml file like below:

<people xmlns="http://xmlns.blabla.com/name" xmlns:abc="http://xmlns-abc.blabla.com/abc"
abc:firstname="jianfeng"
abc:lastname="tian" />

In your xslt, you have to define namespaces in your xsl:stylesheet declaration to make it working:

xmlns:jet="http://xmlns.blabla.com/name"
xmlns:abc="http://xmlns-abc.blabla.com/abc"

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jet="http://xmlns.blabla.com/name"
xmlns:abc="http://xmlns-abc.blabla.com/abc"
exclude-result-prefixes="abc xs xsi xsl">

<xsl:output method="xml" encoding="UTF-8" indent="yes"/>

<xsl:template match="jet:people">
<person>

<xsl:attribute name="firstname">
<xsl:value-of select="@abc:firstname"/>
</xsl:attribute>

<xsl:attribute name="lastname">
<xsl:value-of select="@abc:lastname"/>
</xsl:attribute>

</person>

</xsl:template>
</xsl:stylesheet>

================================================================

If you have an xml file like below:

<people xmlns="http://www.somewhere.com/blabla" >
<person>
<address>
<postcode>110001</postcode>
</address>
<content group="firstname">John</person>
<content group="lastname">Smith</person>
</person>
</people>

In your xslt, you have to define namespaces in your xsl:stylesheet declaration to make it working:

xmlns:jet="http://www.somewhere.com/blabla"


<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jet="http://www.somewhere.com/blabla"
exclude-result-prefixes="jet xsl xsi">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="ISO-8859-1"/>

<xsl:template match="jet:people">
<data>
<postcode>
<xsl:value-of select="jet:person/jet:address/jet:postcode">
</postcode>

<firstname><xsl:value-of select="jet:person/jet:content[@group='firstname']" /></login>
<lastname><xsl:value-of select="jet:person/jet:content[@group='lastname']" /></login>

</data>
</xsl:template>

</xsl:stylesheet>

No comments: