Insert XML document into existing XML with Python

丶灬走出姿态 提交于 2020-01-02 19:15:10

问题


Given these XML documents:

Document 1

<root>
  <element1>
  </element1>
</root>

Document 2

<request>
  <dummyValue>5</dummyValue>
</request>

Using Pythons ElementTree I'd like to insert the second document into the first document so that the result would look as follows.

Resulting document

<root>
  <element1>
    <request>
      <dummyValue>5</dummyValue>
    </request>
  </element1>
</root>

ET.SubElement(element1, request) gives me a serialization error.

Is there a Pythonic way of doing this?


回答1:


SubElement() constructs an Element and then attaches it to the tree. Since you already have request as an Element, you don't need to construct a new one.

Try element1.append(request), like so:

import xml.etree.ElementTree as ET

doc1 = ET.XML('''
<root>
  <element1>
  </element1>
</root>
''')

request = ET.XML('''
<request>
  <dummyValue>5</dummyValue>
</request>
''')

for element1 in doc1.findall('element1'):
    element1.append(request)

ET.dump(doc1)


来源:https://stackoverflow.com/questions/47891089/insert-xml-document-into-existing-xml-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!