UPDATE - XML PARSER IMPLEMENTATION:因为替换特定的<Location> 标记需要修改正则表达式,所以我提供了一个基于 ElementTree 解析器的更通用和更安全的替代实现(如上所述 @ stribizhev 和@Saket Mittal)。
我必须添加一个根元素 <Emps>(以制作有效的 xml 文档,需要根元素),我还选择通过 <city> 标签过滤要编辑的位置(但可能是每个字段) :
#!/usr/bin/python
# Alternative Implementation with ElementTree XML Parser
xml = '''\
<Emps>
<Emp>
<Name>Raja</Name>
<Location>
<city>ABC</city>
<geocode>123</geocode>
<state>XYZ</state>
</Location>
<sal>100</sal>
<type>temp</type>
</Emp>
<Emp>
<Name>GsusRecovery</Name>
<Location>
<city>Torino</city>
<geocode>456</geocode>
<state>UVW</state>
</Location>
<sal>120</sal>
<type>perm</type>
</Emp>
</Emps>
'''
from xml.etree import ElementTree as ET
# tree = ET.parse('input.xml') # decomment to parse xml from file
tree = ET.ElementTree(ET.fromstring(xml))
root = tree.getroot()
for location in root.iter('Location'):
if location.find('city').text == 'Torino':
location.set("isupdated", "1")
location.find('city').text = 'MyCity'
location.find('geocode').text = '10.12'
location.find('state').text = 'MyState'
print ET.tostring(root, encoding='utf8', method='xml')
# tree.write('output.xml') # decomment if you want to write to file
在线可运行版代码here
以前的正则表达式实现
这是使用惰性修饰符.*? 和点所有(?s) 的可能实现:
#!/usr/bin/python
import re
xml = '''\
<Emp>
<Name>Raja</Name>
<Location>
<city>ABC</city>
<geocode>123</geocode>
<state>XYZ</state>
</Location>
</Emp>'''
locUpdate = '''\
<Location isupdated=1>
<city>MyCity</city>
<geocode>10.12</geocode>
<state>MyState</state>
</Location>'''
output = re.sub(r"(?s)<Location>.*?</Location>", r"%s" % locUpdate, xml)
print output
可以在线测试代码here
警告:如果 xml 输入中有多个 <Location> 标记,则正则表达式将它们全部替换为 locUpdate。你必须使用:
# (note the last ``1`` at the end to limit the substitution only to the first occurrence)
output = re.sub(r"(?s)<Location>.*?</Location>", r"%s" % locUpdate, xml, 1)