Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    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' –
like image 305
Moggy Avatar asked Dec 15 '22 09:12

Moggy


1 Answers

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'
like image 62
abarnert Avatar answered Dec 30 '22 21:12

abarnert