0

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)

1 Answer 1

3

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'))
Sign up to request clarification or add additional context in comments.

1 Comment

you, sir, just saved me hours. Hats off to you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.