Access an element in an XML file and edit them using python

Question:

I have a rather sizable xml file that needs to be edited. I am trying to automate the editing process using python. I tried using the ‘xml.etree.ElementTree’ library in python but it seems like I am missing something. Can someone help me with accessing the elements in the file and how I can edit them?

Here is the xml file I am trying to edit.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:ScheduleDocument root()
    tag = root.tag
    attr = root.attrib
    for child in root:
        print(child.tag, child.attrib)
    for i in root.findall('ScheduleTimeSeries'):
        print(i) # This prints nothing as I am not able to access ScheduleTimeSeries
    print(attr)
    for i in root:
        print(i.attrib)
    for j in root.findall('ns2:CurveType'):
        print(j)


if __name__ == '__main__':
    print('Starting main')
    XMLTree()
    print('Main complete')

I am rather new to working with XML files. Can someone tell me what I am missing?
Can someone help me access the elements, say ‘Status’. After accessing it, how can I edit it?

Asked By: Ajith Viswanath

||

Answers:

Here a simple example:

root = ET.parse('your_path.xml')

# Finding
elem = root.find('.//{xxx/xxx}CurveType')
print(elem.attrib["v"])

# Editing
elem.set("v", "new value")
print(elem.attrib["v"])

# Adding
new_elem = ET.SubElement(root.find(".//{xxx/xxx}ScheduleTimeSeries"), "{xxx/xxx}NewElement")
new_elem.text = "added value"

# Writing
with open("ScheduleDocument.xml", "w") as f:
    f.write(ET.tostring(root).decode())
Answered By: Andreas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.