抑制 XML 文件中的命名空间前缀 [英] Suppressing namespace prefix in XML file
本文介绍了抑制 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 处理.我试过这个:
I added the default tag that has Extension attribute with "png" as value using the below lines. On adding the above tag namespace gets added to each tag. I am new in Python, XML handling. I have tried this:
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")
推荐答案
register_namespace()
设置序列化 XML 时使用的前缀.由于您不想要任何前缀,请使用空字符串.
register_namespace()
sets the prefix to be used when serializing the XML. Since you don't want any prefix, use an empty string.
你需要做的就是改变
ET.register_namespace('xmlns',"http://schemas.openxmlformats.org/package/2006/content-types")`
到
ET.register_namespace('',"http://schemas.openxmlformats.org/package/2006/content-types")
这篇关于抑制 XML 文件中的命名空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文