Bypassing namespaces while copying an XML with XSLT

旧城冷巷雨未停 提交于 2020-01-12 05:57:51

问题


Starting from an XML with a default namespace:

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

I apply an XSLT to remove the 'C' element:

<?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>

and I end up with the following XML (it's OK to have 'B' not collapsed because I'm using HTML as output method):

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

But then if I ever get another XML, this time with a namespace:

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

the 'C' element is not removed after XSLT process.

What can I do to bypass this namespace, is there a way?


回答1:


Not so recommendable, but works:

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

Better:

<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>


来源:https://stackoverflow.com/questions/981028/bypassing-namespaces-while-copying-an-xml-with-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!