Replacing XML Element In Python
I am trying to replace the element inside of bbox with a new set of coordinates. my code : # import element tree import xml.etree.ElementTree as ET #import xml file
Solution 1:
The findall
function, as the name implies, finds all matching elements, not just one.
So, after this:
elem = tree.findall('bbox')
elem
is a list of Element
s. And, as with any other list, this:
elem.txt = '40.5,41.5,-12.0,-1.2'
Is going to give you an error:
AttributeError: 'list' object has no attribute 'txt'
If you want to do something to every member of a list, you have to loop over it:
elems = tree.findall('bbox')
for elem in elems:
elem.txt = '40.5,41.5,-12.0,-1.2'
Solution 2:
If your file isn't update it is most likely because you are not saving it, you can use the tree.write
method to do just that.
tree.write('output.xml')
Solution 3:
# import element tree
import xml.etree.ElementTree as ET
#import xml file
tree = ET.parse('C:/highway.xml')
root = tree.getroot()
elems = root.findall(".//bbox")
for elem in elems:
elem.text = '40.5,41.5,-12.0,-1.2'
tree.write('C:/highway.xml')
Solution 4:
If you want to replace the text of all boundingboxes with '40.5,41.5,-12.0,-1.2', try this
bboxes = tree.xpath('//bbox')
for bbox in bboxes:
bbox.text= '40.5,41.5,-12.0,-1.2'
Post a Comment for "Replacing XML Element In Python"