0

I am attempting to add an element to some XML using ElementTree.

<device>
    <general>
        <item1>text</item1>
    </general>
</device>

I want to add <item2>text</item2> under general.

I tried

ElementTree.SubElement(xml, '/device/general/item2')
ElementTree.SubElement(xml, 'general/item2')

to add the field in but both added new lines at the end of the XML rather than adding inside the existing general element.

Any ideas what I'm doing wrong?

2
  • Are you allowed to use beautiful soup? Commented Jul 6, 2018 at 6:21
  • No. I'm inside another Python module and only ElementTree is available to me Commented Jul 6, 2018 at 7:19

1 Answer 1

1

The second argument to SubElement must be the name of a single element; it cannot be a "path" like general/item2. Get a reference to the general element and add a subelement to it.

from xml.etree import ElementTree as ET

tree = ET.parse("device.xml")

general = tree.find(".//general")
item2 = ET.SubElement(general, "item2")
item2.text = "text"
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.