A1122
A1122

Reputation: 1354

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.

FileA.xml

    <FileAServices>
            <Services ref="FileB.xml" xpath="Services"/>
    </FileAServices>

FileB.xml

    <Services>
            <ThreadName>FileBTask</ChangeRequestName>
    </Services>

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.

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)

Upvotes: 0

Views: 1274

Answers (1)

user5386938
user5386938

Reputation:

Just use elem.clear() and 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'))

Upvotes: 3

Related Questions