Replacing XML element in Python

ぃ、小莉子 提交于 2019-12-12 14:32:39

问题


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
    tree = ET.parse('C:/highway.xml')
    root = tree.getroot()

    #replace bounding box with new coordinates

    elem = tree.findall('bbox')
    elem.txt = '40.5,41.5,-12.0,-1.2'

my xml file:

   <geoEtl>
    <source>
        <server>localhost</server>
        <port>xxxx</port>
        <db>vxxx</db>
        <user>xxxx</user>
        <passwd>xxxx</passwd>
    </source>
    <targetDir>/home/firstuser/</targetDir>
    <bbox>-52.50,-1.9,52.45,-1.85</bbox>
    <extractions>
        <extraction>
            <table>geo_db_roads</table>
            <outputName>highways</outputName>
            <filter>highway = 'motorway'</filter>
            <geometry>way</geometry>
            <fields>
                <field>name</field>             
            </fields>
        </extraction>
    </extractions>
   </geoEtl>

have tried a variety of ways to do of things i found here but it doesnt seem to be working. thanks.

The error I'm receiving is as follows:

line 20, in <module> elem.txt = '40.5,41.5,-12.0,-1.2' AttributeError: 'list' object has no attribute 'txt' –

回答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 Elements. 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'



回答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')



回答3:


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'



回答4:


# 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')


来源:https://stackoverflow.com/questions/17437103/replacing-xml-element-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!