从 xml 中删除所有命名空间

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

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

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


萧十郎
浏览 206回答 1
1回答

墨色风雨

您可以通过从 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">&nbsp; &nbsp; <xsl:output method="xml" indent="yes"/>&nbsp; &nbsp; <xsl:template match="node()|@*">&nbsp; &nbsp;<!-- Identity template copies all nodes (except for elements, which are handled by the other template) -->&nbsp; &nbsp; &nbsp; &nbsp; <xsl:copy>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <xsl:apply-templates select="node()|@*" />&nbsp; &nbsp; &nbsp; &nbsp; </xsl:copy>&nbsp; &nbsp; </xsl:template>&nbsp; &nbsp; <xsl:template match="*">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<!-- Removes all namespaces from all elements -->&nbsp; &nbsp; &nbsp; &nbsp; <xsl:element name="{local-name()}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <xsl:apply-templates select="node()|@*" />&nbsp; &nbsp; &nbsp; &nbsp; </xsl:element>&nbsp; &nbsp; </xsl:template></xsl:stylesheet>将其与 XSLT-1.0(或更高版本)框架/处理器一起应用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python