Python xml find element by tag value
I am using python xmlElementTree and want to assign or modify a xml element value based on its attribute. Can somebody give me an idea how to do this? Show For example: Here is a xml file and I need to set the value for the element "number" based on the attribute "sys/phoneNumber/1", "sys2/SMSnumber/1" and so on.
edit: Added closure for the tag root in the XML file.
1stthomas 7212 gold badges15 silver badges22 bronze badges asked Mar 21, 2012 at 1:03
You can access the attribute value as this:
forget to say, if your ElementTree version is greater than 1.3, you can use XPath:
http://effbot.org/zone/element-xpath.htm or you can use this simple one:
answered Mar 21, 2012 at 1:35
focusheartfocusheart 3272 silver badges3 bronze badges 4 For me this Elementtree snipped of code worked to find element by attribute:
answered Feb 28, 2019 at 20:15
Eduard FlorinescuEduard Florinescu 15.6k28 gold badges108 silver badges171 bronze badges I'm not familiar with
So, using the
answered Mar 21, 2012 at 1:16
larskslarsks 241k37 gold badges358 silver badges348 bronze badges larsks explains how to use XPath to find what you are after very well. You also wanted to change an attribute. The best way is probably to add a new attribute and remove the original. Once you get the nodes result, it is a list with a single entry (number).
Hope this helps. Also, your ending root tag doesn't close properly. answered Mar 21, 2012 at 1:58
How do I find a specific tag in XML in Python?Use xml.. tree = ElementTree. parse("sample.xml"). root = tree. getroot(). dogs = root. findall("dog"). for dog in dogs:. print(dog. text). How do I find tags in XML?If you use findAll for the root element of the tree, it searches all subelements. You can also use it on the ElementTree object, instead of the root element, and then it also searches the root.
How do you add a tag to XML in Python?Add them using Subelement() function and define it's text attribute.. child=xml. Element("employee") nm = xml. SubElement(child, "name") nm. text = student. ... . import xml. etree. ElementTree as et tree = et. ElementTree(file='employees.xml') root = tree. ... . import xml. etree. ElementTree as et tree = et.. |