【发布时间】:2021-09-28 11:25:50
【问题描述】:
输入文件:
<?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 来完成这样的任务?
-
如果可以的话,使用 lxml 代替 elementttree。
标签: python xml elementtree xml-namespaces