Python Forum
Python to update XML SubElement - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python to update XML SubElement (/thread-11940.html)



Python to update XML SubElement - emersonivo - Aug-01-2018

Hi all,

I am looking for this help everywhere in the past days without success and I hope someone here can share some knowledge.
In the XML data below, how do I do for:
1 - Update the {id="012345"/res name="attrib1"/last_seem key} 'date' and 'status' attributes?
2 - Delete the {id="012345"/res name="attrib2}
3 - Add a new {id="123456"/res name="attrib2"} with 'first_seem' and 'last_seem' keys and values

Important:
- I am going to have hundred different users/IDs
- I am going to have dozens res/attributes

<stop>
<user id="012345">
<res name="attrib1">
<first_seem date="2018-07-31" status="REQUESTED">1</first_seem>
<last_seem date="2018-07-31" status="INPROCESS">0</last_seem>
</res>
<res name="attrib2">
<first_seem date="2018-07-31" status="REQUESTED">1</first_seem>
<last_seem date="2018-07-31" status="COMPLETED">0</last_seem>
</res>
</user>
<user id="123456">
<res name="attrib1">
<first_seem date="2018-07-31" status="REQUESTED">1</first_seem>
<last_seem date="2018-07-31" status="REQUESTED">0</last_seem>
</res>
</user>
</stop>

So far I found help to update values in a fixed path (i.e: /root/user/res/lastseem.text), what did not help me.
I tried to use the same command used to create the XML above changing a single/desired value, but instead of update, Python created a new entry Sad

Thank you so much for any help.


RE: Python to update XML SubElement - Larz60+ - Aug-01-2018

you need to learn how to use lxml (XML parser) see: https://www.blog.pythonlibrary.org/2010/11/20/python-parsing-xml-with-lxml/


RE: Python to update XML SubElement - emersonivo - Aug-01-2018

Thank you Larz60+

Actually I am learning how to parse (read) XML records, what I am not finding anywhere (nowhere), including in the link you shared is 'How to update subelements attributes'.


RE: Python to update XML SubElement - Larz60+ - Aug-02-2018

see: https://docs.python.org/3.7/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set