【问题标题】:Remove all tags from unwanted Namespaces从不需要的命名空间中删除所有标签
【发布时间】:2018-11-16 21:20:07
【问题描述】:

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

但有些确实有来自不在我们列表中的命名空间的“扩展” - 所以我们的 jaxb 解析器崩溃了。

是否有任何 XSL 可以删除所有不在白名单上的命名空间及其标签?

【问题讨论】:

  • 删除到底是什么意思?如果您的命名空间中有一个元素不在您的白名单上,但它在白名单上有子元素或后代,您是要完全删除该元素还是要保留子元素/后代?
  • 您说的是“标签”,但您的意思是元素(或节点)。此外,命名空间不能被“删除”。您可以删除在(或不在)给定命名空间中的节点。或者您可以将它们移动到不同的命名空间。

标签: xml xslt jaxb tags


【解决方案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>

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 2020-08-30
    • 2011-05-14
    • 2013-02-19
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多