Tony Williams
Tony Williams

Reputation: 647

Adding an element to XML with ElementTree

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?

Upvotes: 0

Views: 99

Answers (1)

mzjn
mzjn

Reputation: 51062

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"

Upvotes: 1

Related Questions