【问题标题】:Find and replace in xml file with Python用Python在xml文件中查找和替换
【发布时间】:2015-02-17 09:45:02
【问题描述】:

我对 Python 真的很陌生。 我有一个里面有 html 的 xml 文件和一个 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 

但它不会替换所有值。

提前致谢。

【问题讨论】:

    标签: python xml csv


    【解决方案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 数据中的转义或引用的复杂性。

    【讨论】:

    • 感谢您理解我错误的html代码并回答它。刚才我编辑了我的代码。我接受你的回答。
    猜你喜欢
    • 2014-08-17
    • 1970-01-01
    • 2019-10-16
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多