Subject: Re: [xsl] Namespaces and template matching From: David N Bertoni/Cambridge/IBM <david_n_bertoni@xxxxxxxxxx> Date: Thu, 7 Nov 2002 21:19:18 -0800 |
> I am struggling with doing a template match when namespaces are > involved. > > I have the following stylesheet which renames any 'x' element to 'y': > > <?xml version='1.0' encoding='UTF-8'?> > <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > version="1.0"> > <xsl:template match="x"> > <xsl:element name="y"> > <xsl:apply-templates select="@*"/> > <xsl:apply-templates/> > </xsl:element> > </xsl:template> > <xsl:template match="@*|node()"> > <xsl:copy> > <xsl:apply-templates select="@*"/> > <xsl:apply-templates/> > </xsl:copy> > </xsl:template> > </xsl:stylesheet> > ... > > <?xml version="1.0" encoding="UTF-8"?> > <a> > <x a="1" b="2" c="3" d="4" /> > </a> > ... > > <?xml version="1.0" encoding="UTF-8"?> > <a xmlns="b"> > <x a="1" b="2" c="3" d="4" /> > </a> I'm sure this is a FAQ. You're matching elements named "x" which have a null namespace URI. Your second document contains an element x, but, because it has no prefix, and there's a default namespace, it's namespace URI is "b", so the template doesn't match. However, the second template matches (which defines an identity transformation), so the document is copied. If you want to match "x" elements with a namespace URI of "b", you should define a template that matches them: <?xml version='1.0' encoding='UTF-8'?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:foo="b" version="1.0"> <xsl:template match="foo:x"> <xsl:element name="y"> <xsl:apply-templates select="@*"/> <xsl:apply-templates/> </xsl:element> </xsl:template> ... If you want to match all elements with a local name of "x", you could do the following: <xsl:template match="*[local-name() = 'x']"> <xsl:element name="y" namespace="{namespace-uri()}"> <xsl:apply-templates select="@*"/> <xsl:apply-templates/> </xsl:element> </xsl:template> Note this template is also creating the "y" element in the same namespace as the "x" element. Whether or not that's appropriate is application-specific, but if you leave it out, you're liable to get results which might puzzle you. Hope that helps... Dave XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
[xsl] Namespaces and template match, David P. Nesbitt | Thread | RE: [xsl] Namespaces and template m, Michael Kay |
[xsl] Namespaces and template match, David P. Nesbitt | Date | [xsl] Recall: Character esca, Schwartz, Rechell R, |
Month |