本文介绍了替换Python中的XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用一组新的坐标替换bbox内的元素。
I am trying to replace the element inside of bbox with a new set of coordinates.
我的代码:
# 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>尝试了多种方法来处理我在此处发现的问题,但似乎没有用。
have tried a variety of ways to do of things i found here but it doesnt seem to be working. thanks.
我收到的错误如下:
line 20, in <module> elem.txt = '40.5,41.5,-12.0,-1.2' AttributeError: 'list' object has no attribute 'txt' –推荐答案
findall 函数,顾名思义,可以找到 all 个匹配元素,而不仅仅是
The findall function, as the name implies, finds all matching elements, not just one.
因此,在此之后:
elem = tree.findall('bbox')elem 是元素的列表。并且,与其他任何列表一样,
elem is a list of Elements. And, as with any other list, this:
elem.txt = '40.5,41.5,-12.0,-1.2'会给你一个错误:
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'更多推荐
替换Python中的XML元素
发布评论