如何解决抑制 XML 文件中的命名空间前缀
输入文件:
<?xml version="1.0" encoding="utf-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="json" ContentType=""/>
<Override PartName="/Version" ContentType=""/>
</Types>
我得到的输出:
<?xml version='1.0' encoding='utf-8'?>
<xmlns:Types xmlns:xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<xmlns:Default Extension="json" ContentType=""/>
<xmlns:Override PartName="/Version" ContentType=""/>
<xmlns:Default Extension="png" ContentType=""/>
</xmlns:Types>
所需输出:
<?xml version="1.0" encoding="utf-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="json" ContentType=""/>
<Override PartName="/Version" ContentType=""/>
<Default Extension="png" ContentType=""/>
</Types>
我使用以下几行添加了具有“png”作为值的扩展属性的默认标签。添加上述标签命名空间后,将添加到每个标签中。我是 Python 新手,XML 处理。我试过这个:
import xml.etree.ElementTree as ET
def formatxml():
dest="input.xml"
tree = ET.parse(dest)
root = tree.getroot()
ET.register_namespace('xmlns',"http://schemas.openxmlformats.org/package/2006/content-types")
child=ET.SubElement(root,"{http://schemas.openxmlformats.org/package/2006/content- types}Default")
child.set('Extension',"png")
child.set('ContentType',"")
tree.write(dest,xml_declaration=True,encoding='utf-8',method="xml")
解决方法
这里是如何使用 XSLT 来完成任务。
XSLT 遵循所谓的身份转换模式。
输入 XML
<?xml version="1.0" encoding="utf-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="json" ContentType=""/>
<Override PartName="/Version" ContentType=""/>
</Types>
XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="http://schemas.openxmlformats.org/package/2006/content-types" exclude-result-prefixes="ns1">
<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="ns1:Override">
<xsl:copy-of select="."/>
<Default Extension="png" ContentType=""/>
</xsl:template>
</xsl:stylesheet>
输出 XML
<?xml version='1.0' encoding='utf-8' ?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="json" ContentType=""/>
<Override PartName="/Version" ContentType=""/>
<Default Extension="png" ContentType=""/>
</Types>
,
register_namespace()
设置序列化 XML 时要使用的前缀。由于您不想要任何前缀,请使用空字符串。
你需要做的就是改变
ET.register_namespace('xmlns',"http://schemas.openxmlformats.org/package/2006/content-types")`
到
ET.register_namespace('',"http://schemas.openxmlformats.org/package/2006/content-types")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。