Subject: Re: How to output the unused namespaces in the XML document?
From: Michael Kay <mike@xxxxxxxxxxxx>
Date: Mon, 30 Aug 2010 22:28:41 +0100
|
It isn't possible to know whether a namespace is unused. I think what
you mean is "not used in any element or attribute name".
The simple answer to that in XPath 2.0 is
distinct-values(//namespace::*[not(. = //*/namespace-uri() or . =
//@*/namespace-uri())]).
However, your code is testing something different. Given this source
document
<?xml version="1.0"?>
<N1:NumberList>
<Number>23</Number>
<Number>41</Number>
<Number xmlns:N3="http://www.example3.org">70</Number>
<N3:Number xmlns:N3="http://www.example3.org">103</Number>
<Number>99</Number>
<Number>6</Number>
</N1:NumberList>
You will report http://www.example3.org as unused because there is a
declaration of this namespace that is not used in any ancestor or
descendant of the element where it is declared; my code considers it as
used because there is an element where it is used. As usual, it all
comes down to careful specification of your problem.
Michael Kay
Saxonica
Hi Folks,
Consider this XML document:
<?xml version="1.0"?>
<N1:NumberList xmlns:N1="http://www.example1.org"
xmlns:N2="http://www.example2.org">
<Number>23</Number>
<Number>41</Number>
<Number xmlns:N3="http://www.example3.org">70</Number>
<Number>103</Number>
<Number>99</Number>
<Number>6</Number>
</N1:NumberList>
Notice that there are three (3) namespaces, but two of them are unused:
http://www.example2.org
http://www.example3.org
I want an XSLT transform that will output all the unused namespaces in the input XML document.
Here's the solution I came up with:
<xsl:template match="*">
<xsl:variable name="elem" select="." />
<xsl:for-each select="namespace::*[. != 'http://www.w3.org/XML/1998/namespace']">
<xsl:variable name="ns" select="." />
<xsl:if test="not($elem/ancestor::*[namespace::* = $ns])">
<xsl:if test="not($elem/descendant-or-self::*[namespace-uri() = $ns])">
This namespace is unused:<xsl:value-of select="$ns" />
</xsl:if>
</xsl:if>
</xsl:for-each>
<xsl:apply-templates select="*" />
</xsl:template>
Is there a better solution? (I am using XSLT 1.0)
/Roger
|