0

I'm parsing the following XML file using xml.etree.ElementTree:

<main>
    <stream id="1" name="some">
        <inner id="500">
              <sub-inner>
                 <inside> 500 </inside>
              <sub-inner>
        <inner>
    <stream id="2" name="some">
        <inner id="500">
              <sub-inner>
                 <inside> 500 </inside>
              <sub-inner>
        <inner>
    </stream>
</main>

How do I insert <outer>200</outer> element into the < sub-inner> tag where stream id ="2" one?

1 Answer 1

2
import xml.etree.ElementTree as ET

root = ET.fromstring('''
<main>
    <stream id="1" name="some">
        <inner>500</inner>
    </stream>
    <stream id="2" name="some">
        <inner>500</inner>
    </stream>
</main>''')
stream = root.find('.//stream[@id="2"]')
outer = ET.SubElement(stream, 'outer')
outer.text = '200'
print(ET.tostring(root))

output:

<main>
    <stream id="1" name="some">
        <inner>500</inner>
    </stream>
    <stream id="2" name="some">
        <inner>500</inner>
    <outer>200</outer></stream>
</main>

If you want outer to come before the inner:

...
stream = root.find('.//stream[@id="2"]')
outer = ET.Element('outer')
outer.text = '200'
stream.insert(0, outer)
print(ET.tostring(root))

output:

<main>
    <stream id="1" name="some">
        <inner>500</inner>
    </stream>
    <stream id="2" name="some">
        <outer>200</outer><inner>500</inner>
    </stream>
</main>
Sign up to request clarification or add additional context in comments.

Comments

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.