当XML元素在for
循环中ET.interparse()
时,我试图为它编写一个新的属性值。如何做到这一点的建议
我希望避免打开整个XML文件,因为它相当大,这就是为什么我一次只在开始事件中打开一个元素的原因
以下是我的代码:
import xml.etree.cElementTree as ET
def main_function:
osmfile = 'sample.osm'
osm_file = open(osmfile, 'r+')
for event, elem in ET.interparse(osm_file, events=('start',)):
if elem.tag == 'node':
for tag in elem.iter('tag'):
if is_addr_street_tag(tag): # Function returns boolean
cleaned_street_name = cleaning_street(tag.attrib['v']) # Function returns cleaned street name
##===================================================##
## Write cleaned_street_name to XML tag attrib value ##
##===================================================##
osm_file.close()
BLUF:显然,如果不打开整个XML文件,然后再重写整个XML文件,就不可能做到这一点
1)您不能将属性写回元素(虽然您确实可以,但这将很困难、耗时且不美观)
2)“如果不重写整个文件,用较短或较长的文本替换文件中的文本在物理上是不可能的(唯一的例外是“长度完全相同的文本”和“数据在最末尾”。)
下面是usr2564301对一个与您的问题相关的问题的评论,该问题涉及在不打开整个XML文档的情况下更改元素的属性值
相关问题 更多 >
编程相关推荐