PYTHON:如何将根节点添加到XML

问题描述:

我有一个看起来像这样的xml文件

I have an xml file looks something like this

<A>
  <B>
     <C>
       ....
     </C>
  </B>
</A>

我想在元素'A'上添加根.我找到了一种将元素添加到根目录的方法.但是如何更改现有的根并使用python在其上添加.

I want to add root on top of element 'A'. I found out a way to add elements to root. But How to change existing root and add on top of it using python.

将root添加到xml后,它应该看起来像这样

After adding root to the xml it should look like this

<ROOT>
  <A>
    <B>
       <C>
         ....
       </C>
    </B>
  </A>
</ROOT>

import lxml.etree as ET
tree = ET.parse('data')
root = tree.getroot()
newroot = ET.Element("root")
newroot.insert(0, root)
print(ET.tostring(newroot, pretty_print=True))

收益

<root>
  <A>
  <B>
     <C>
       ....
     </C>
  </B>
</A>
</root>


但是,实际上,除非您需要添加更复杂的内容,否则简单的字符串格式就足够了:


But really, unless you need to add something more complicated, simple string formatting could suffice:

with open('data', 'rb') as f, open('newdata', 'wb') as g:
    g.write('<ROOT>{}</ROOT>'.format(f.read()))