首页 > 解决方案 > 从 xml 中删除所有命名空间

问题描述

有没有办法从 xml 中删除名称空间(我知道没有任何名称冲突)?目前我正在为每个已知的命名空间执行此操作:

s = re.sub(r'(<\/?)md:', r'\1', s)             # remove md:
s = re.sub(r'\s+xsi:', ' ', s)                 # remove xsi:

但我想知道是否有更通用的东西可以使用。特定 xml 中不允许使用 CDATA。

标签: pythonregexxml

解决方案


您可以通过从 Python 调用以下 XSLT-1.0 模板来使用 XSLT 方法。它将标识模板name()将元素的(完整)s转换为local-name()仅它们的 s 的模板相结合。例如,这意味着所有<ns1:abc>元素都转换<abc>为 。命名空间被省略。

但是,这有多有用取决于您的用例。它减少了信息量,因此请小心处理。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="node()|@*">   <!-- Identity template copies all nodes (except for elements, which are handled by the other template) -->
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*">           <!-- Removes all namespaces from all elements -->
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="node()|@*" />
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

将它与 XSLT-1.0(或更高版本)框架/处理器一起应用。


推荐阅读