1

I have an xml file looks something like this

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

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.

After adding root to the xml it should look like this

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

1 回答 1

6
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>

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

with open('data', 'rb') as f, open('newdata', 'wb') as g:
    g.write('<ROOT>{}</ROOT>'.format(f.read()))
于 2014-09-07T21:21:27.763 回答