我正在尝试用一组新坐标替换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' –
答案 0 :(得分:5)
findall
函数,顾名思义,找到所有匹配元素,而不只是一个。
所以,在此之后:
elem = tree.findall('bbox')
elem
是Element
的列表。并且,与任何其他列表一样,这个:
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'
答案 1 :(得分:3)
如果你的文件没有更新,很可能是因为你没有保存它,你可以使用tree.write
方法来做到这一点。
tree.write('output.xml')
答案 2 :(得分: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'
答案 3 :(得分:0)
# 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')