在 xml 文件中查找并替换为 Python

Find and replace in xml file with Python

我真的是 Python 的新手。 我有一个 xml 文件,里面有 html 和一个 csv 文件。

xml 文件示例:

<example>
  <name id="{{2}}">{{1}}</name>
  <class>{{3}}</class>
    <modules>
      <module>{{4}}</module>
      <module>{{5}}</module>
      <module>{{6}}</module>
    </modules>
</example>

包含两列的 CSV 文件:

1;Alex
2;345
3;10
4;math
5;pysics
6;chemistry

我必须用 csv 文件第二列中的值替换 {{}} 中的值(引用在第一列的 csv 文件中)。

我能够成功读取 csv 文件(没问题)。 我正在寻找针对每个 {{}}.

在 xml 文件中查找和替换的解决方案

我试过了

  i=1
  for line in inputfile.readlines():
     outputfile.write(line.replace('{{'+str(i)+'}}', 'value from 2nd colum of csv file'))
     i = i +1 

但它并没有替换所有值。

提前致谢。

这段代码应该可以解决问题:

from csv import reader

with open('test.xml') as inputfile:
    xml = inputfile.read()

with open('test.csv') as csvfile:
    for row in reader(csvfile, delimiter=';'):
        xml = xml.replace('{{%s}}' % row[0], row[1])

with open('output.xml', 'w') as outputfile:
    outputfile.write(xml)

此代码使用 csv 模块,这意味着您不必处理可能出现在 csv 数据中的转义或引用的复杂性。