从不需要的命名空间中删除所有标签

时间:2018-11-16 21:20:08

标签: xml xslt jaxb tags

我想解析用户的XML文件。它们可能包含来自XML NS-URL的已定义列表的标记。

但是有些确实具有不在我们列表中的名称空间的“扩展名”-因此我们的jaxb-parser崩溃了。

是否有XSL可以删除所有不在白名单上的名称空间及其标记?

1 个答案:

答案 0 :(得分:1)

考虑以下示例:

XML

<root xmlns="http://www.example.com/a">
    <item xmlns="http://www.example.com/b">
        <sub-item>bravo</sub-item>
    </item>
    <item xmlns="http://www.example.com/x">
        <sub-item>x-ray</sub-item>
    </item>
    <item xmlns="http://www.example.com/c">
        <sub-item>charlie</sub-item>
    </item>
</root>

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="http://www.example.com/my"
exclude-result-prefixes="my">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<my:allowed-namespaces>
    <uri>http://www.example.com/a</uri>
    <uri>http://www.example.com/b</uri>
    <uri>http://www.example.com/c</uri>
</my:allowed-namespaces>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*[not(namespace-uri()=document('')/xsl:stylesheet/my:allowed-namespaces/uri)]"/>

</xsl:stylesheet>

结果

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.example.com/a">
  <item xmlns="http://www.example.com/b">
    <sub-item>bravo</sub-item>
  </item>
  <item xmlns="http://www.example.com/c">
    <sub-item>charlie</sub-item>
  </item>
</root>
相关问题