[英]Insert an xml file in a node of another xml file using Python ElementTree
I have two xml files, where A references B. I would like a way to combine them into single xml file in Python.我有两个 xml 文件,其中 A 引用 B。我想要一种方法将它们组合成 Python 中的单个 xml 文件。
FileA.xml文件A.xml
<FileAServices>
<Services ref="FileB.xml" xpath="Services"/>
</FileAServices>
FileB.xml文件B.xml
<Services>
<ThreadName>FileBTask</ChangeRequestName>
</Services>
Output Output
<FileAServices>
<Services>
<ThreadName>FileBTask</ThreadName>
</Services>
</FileAServices>
I've only gotten as far as below.我只到了下面。 I don't know how to assign the entire tree to elem.
我不知道如何将整个树分配给 elem。
import xml.etree.ElementTree as ET
base = ET.parse('FileA.xml')
ref = ET.parse('FileB.xml')
root = base.getroot()
subroot = ref.getroot()
for elem in root.iter('Services'):
elem.attrib = {}
for subelem in subroot.iter():
subdata = ET.SubElement(elem, subelem.text)
if subelem.attrib:
for k, v in subelem.attrib.items():
subdata.set(k, v)
Just use elem.clear()
and elem.append(...)
.只需使用
elem.clear()
和elem.append(...)
。
from io import StringIO, BytesIO
import xml.etree.ElementTree as ET
a = b'''\
<FileAServices>
<Services ref="FileB.xml" xpath="Services"/>
</FileAServices>\
'''
b = b'''\
<Services>
<ThreadName>FileBTask</ThreadName>
</Services>\
'''
base = ET.parse(BytesIO(a))
ref = ET.parse(BytesIO(b))
root = base.getroot()
subroot = ref.getroot()
elem = root.find('Services')
elem.clear()
for subelem in subroot.iter('ThreadName'):
elem.append(subelem)
out = BytesIO()
base.write(out, 'UTF-8')
print(out.getvalue().decode('UTF8'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.