替换Python中的XML元素

编程入门 行业动态 更新时间:2024-10-27 16:36:32
本文介绍了替换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元素

本文发布于:2023-11-10 15:40:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575771.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   Python   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!