通过python中的XML.osm在ET.iterpase()时更改attrib值

2024-10-01 02:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

当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()

Tags: namein元素streetforifosmtag
1条回答
网友
1楼 · 发布于 2024-10-01 02:25:56

BLUF:显然,如果不打开整个XML文件,然后再重写整个XML文件,就不可能做到这一点

1)您不能将属性写回元素(虽然您确实可以,但这将很困难、耗时且不美观)

2)“如果不重写整个文件,用较短或较长的文本替换文件中的文本在物理上是不可能的(唯一的例外是“长度完全相同的文本”和“数据在最末尾”。)

下面是usr2564301对一个与您的问题相关的问题的评论,该问题涉及在不打开整个XML文档的情况下更改元素的属性值

That cannot possibly work. The XML handling is unaware that the data came from a file and so it cannot "write back" the changed value at the exact same position in the file. Even if it could: it is physically impossible to replace a text in a file with a shorter or longer text without rewriting the entire file. (The very only exceptions being "exactly the same length text" and "the data is at the very end".) – usr2564301

相关问题 更多 >