python - 从 xml 中删除所有命名空间
问题描述
有没有办法从 xml 中删除名称空间(我知道没有任何名称冲突)?目前我正在为每个已知的命名空间执行此操作:
s = re.sub(r'(<\/?)md:', r'\1', s) # remove md:
s = re.sub(r'\s+xsi:', ' ', s) # remove xsi:
但我想知道是否有更通用的东西可以使用。特定 xml 中不允许使用 CDATA。
解决方案
您可以通过从 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(或更高版本)框架/处理器一起应用。
推荐阅读
- java - 转到 RecyclerView 上选择的项目
- amazon-web-services - AWS CLI cp 不会第二次复制文件
- mysql - 将 CONSTRAINT 与 FOREIGN KEY 一起使用
- windows - 八度包安装在 Windows 上不成功
- python - Spark RDD - 发送迭代器时出错
- gradle - 检查 Gradle 系统属性是否已设置
- regex - REGEX PCRE - 避免字符串和括号内任何字符串的第一个实例
- php - File_get_contents 无法打开流:http 请求失败 404 未找到
- magento-1.9 - PHP 致命错误未捕获错误:在 null 上调用成员函数 getMetaTitle()
- sql - 表结构问题 - Query Pivot/Unpivot