Py学习  »  Python

在xml文件中找到一行,并使用python将下一行替换为其他内容

moong • 7 年前 • 1987 次点击  

使用python,当上面的行匹配时,我需要替换xml文件中的行。

    <groupId>test</groupId>
    <artifactId>dmrfolder</artifactId>
    <version>1.0</version>

我想在这里搜索 dmrfolder 如果找到了,我需要更换下面的 1.0 具有 somevalue .

我按下面的方法走,但对我不起作用。

with open('test.xml', 'r') as file :
            data = file.read()
            fnl = data.replace(line[1], str)
            with open('test.xml', 'w') as fw:
               fw.write(fnl)
               fw.close()

预期的结果是

    <groupId>test</groupId>
    <artifactId>dmrfolder</artifactId>
    <version>somevalue</version>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44249
文章 [ 2 ]  |  最新文章 7 年前
Armali
Reply   •   1 楼
Armali    7 年前

如果数据文件格式与发布的格式完全相同(包括间距),则可以使用 .replace() :

        fnl = data.replace('''dmrfolder</artifactId>
    <version>1.0''', '''dmrfolder</artifactId>
    <version>somevalue''')

对于变量或不知名的格式,可以使用 re.sub() :

        fnl = re.sub('(dmrfolder</artifactId>\s*<version>)1.0', r'\1somevalue', data)
  • \s -任何空白字符,包括 \n
  • \1 -第一个(这里:唯一的)括号组
cody
Reply   •   2 楼
cody    7 年前

你可以用 lxml 的 getnext() 修改每个 artifactId 元素的方式如下:

import lxml.etree

xml = """
<xml>
  <groupId>test</groupId>
  <artifactId>dmrfolder</artifactId>
  <version>1.0</version>
</xml>
"""

root = lxml.etree.fromstring(xml)
for e in root.findall("artifactId"):
    e.getnext().text = "somevalue"

print(lxml.etree.tostring(root, encoding="unicode"))

结果:

<xml>
  <groupId>test</groupId>
  <artifactId>dmrfolder</artifactId>
  <version>somevalue</version>
</xml>