使用XSLT复制XML时绕过名称空间

时间:2009-06-11 13:19:53

标签: java xml xslt

从具有默认命名空间的XML开始:

<Root>
  <A>foo</A>
  <B></B>
  <C>bar</C>
</Root>

我应用XSLT删除'C'元素:

<?xml version="1.0" ?>

<xsl:stylesheet version="2.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="html" indent="no" encoding="utf-8" />

<xsl:template match="*">
        <xsl:copy>
                <xsl:copy-of select="@*" />
                <xsl:apply-templates />
        </xsl:copy>
</xsl:template>

<xsl:template match="C" />

</xsl:stylesheet>

我最终得到了以下XML(可以让'B'没有崩溃,因为我使用HTML作为输出方法):

<Root>
  <A>foo</A>
  <B></B>
</Root>

但是如果我得到另一个XML,这次使用命名空间:

<Root xmlns="http://company.com">
  <A>foo</A>
  <B></B>
  <C>bar</C>
</Root>

在XSLT进程之后,不会删除'C'元素。

我可以做些什么来绕过这个命名空间,有办法吗?

1 个答案:

答案 0 :(得分:9)

不太值得推荐,但有效:

<xsl:template match="*[local-name()='C']" />

更好:

<xsl:stylesheet 
  version="2.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:foo="http://company.com"
  exclude-result-prefixes="foo"
>

  <!-- ... -->

  <xsl:template match="C | foo:C" />

  <!-- ... -->

</xsl:stylesheet>