简体   繁体   English

使用libxml2 Python绑定设置XML根目录

[英]Set XML root with libxml2 Python bindings

I have the following XML 我有以下XML

<Head>
<child></child>
</Head>

And I want to alter the XML to something like this: 我想将XML更改为以下形式:

<Parent>
<child></child>
</Parent>

How do I do this? 我该怎么做呢? I have read this and this but they use Element tree. 我已阅读这个这个 ,但他们使用的元素树。

For instance, you have this original file. 例如,您有此原始文件。

<Head>
<child>this is text for child</child>
</Head>

Then you can use xml.dom.minidom to change name of root tag. 然后,您可以使用xml.dom.minidom更改根标记的名称。

#-*- coding:utf-8 -*-
#!/usr/bin/env python


import xml.dom.minidom

info = '''
<Head>
<child>this is text for child</child>
</Head>
'''

dom = xml.dom.minidom.parseString(info)
dom.firstChild.tagName = 'parent'
# save it to any file you want
xml_file = 'C:\\temp\\lch.xml'
f = open(xml_file, 'wb')
dom.writexml(f)
f.close()

OUTPUT: OUTPUT:

<?xml version="1.0" ?><parent>
<child>this is text for child</child>
</parent>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM