使用python正则表达式编辑xml文件

时间:2012-12-12 15:36:17

标签: python regex

我有一个xml文件,如下所示

<?xml version="1.0" encoding="utf-8"?>
<myTable xmlns="http://schemas.microsoft.com/windows/2008">
  <my id="1">Hi this is one</my>
  <my id="2">Hi this is one</my>
  <my id="6">Hi this is one</my> 
  <my id="7">Hi this is one</my>
   <my id="8">Hi this is one</my>
   <my id="9">Hi this is one</my>
</myTable>

我想将(1)追加到第一个'我的id =“1”'。所以我的结果xml将如下所示

<?xml version="1.0" encoding="utf-8"?>
<myTable xmlns="http://schemas.microsoft.com/windows/2008">
  <my id="1">Hi this is one(1)</my>
  <my id="2">Hi this is one</my>
  <my id="6">Hi this is one</my> 
  <my id="7">Hi this is one</my>
   <my id="8">Hi this is one</my>
   <my id="9">Hi this is one</my>
 </myTable>

我想在python正则表达式

中完成这件事

由于

2 个答案:

答案 0 :(得分:0)

import re

r = re.compile(r'(<my id="1">.*)(</my>)')

with open(infilename, 'r') as infile, open(newfile, 'w+') as outfile:
    for line in infile:
        match = r.search(line)
        if match:
            f.write(match.group(1) + '(1)' + match.group(2))
        else:
            f.write(line)

你想要什么?

这会搜索具有给定模式的行,如果匹配,则会获取其内容并在其间插入一些内容。

答案 1 :(得分:-1)

创建新文件可以吗?如果是,那么:

import re

f = open(newfile, 'w+')

for line in open(your_file, 'r');
  match = re.search(r'id="1"', line)
  if match:
    f.write('<my id="1">Hi this is one(1)</my>')
  else:
    f.write(line)

f.close()