5

我正在尝试用一组新的坐标替换 bbox 内的元素。

我的代码:

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

我的 xml 文件:

   <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>

已经尝试了多种方法来做我在这里找到的事情,但它似乎不起作用。谢谢。

我收到的错误如下:

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

4 回答 4

8

findall顾名思义,该函数查找所有匹配的元素,而不仅仅是一个。

所以,在这之后:

elem = tree.findall('bbox')

elemElements 的列表。而且,与任何其他列表一样,这是:

elem.txt = '40.5,41.5,-12.0,-1.2'

会给你一个错误:

AttributeError: 'list' object has no attribute 'txt'

如果你想对列表的每个成员做一些事情,你必须循环它:

elems = tree.findall('bbox')
for elem in elems:
    elem.txt = '40.5,41.5,-12.0,-1.2'
于 2013-07-02T22:55:53.953 回答
3

如果您的文件没有更新,很可能是因为您没有保存它,您可以使用该tree.write方法来做到这一点。

tree.write('output.xml')
于 2013-07-02T23:15:05.190 回答
1
# 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')
于 2016-12-12T14:25:55.910 回答
0

如果你想用'40.5,41.5,-12.0,-1.2'替换所有边界框的文本,试试这个

bboxes = tree.xpath('//bbox')
for bbox in bboxes:
    bbox.text= '40.5,41.5,-12.0,-1.2'
于 2013-07-02T22:56:05.857 回答