![](/img/trans.png)
[英]Removing a tag and its contents in xml using BeautifulSoup and lxml in Python
[英]Replace xml tag contents using python
我有一个包含一些数据的xml文件。
<Emp>
<Name>Raja</Name>
<Location>
<city>ABC</city>
<geocode>123</geocode>
<state>XYZ</state>
</Location>
<sal>100</sal>
<type>temp</type>
</Emp>
因此xml文件中的位置信息有误,我必须将其替换。
我在python中用更正的值构造了位置信息。
variable = '''
<Location isupdated=1>
<city>MyCity</city>
<geocode>10.12</geocode>
<state>MyState</state>
</Location>'''
因此,应该用新信息替换位置标签。 有没有简单的方法可以在python中更新它。
我想要最终结果数据,例如
<Emp>
<Name>Raja</Name>
<Location isupdated=1>
<city>MyCity</city>
<geocode>10.12</geocode>
<state>MyState</state>
</Location>
<sal>100</sal>
<type>temp</type>
</Emp>
有什么想法吗 ??
谢谢。
更新 -XML解析器的实现:由于替换特定的<Location>
标记需要修改正则表达式,因此我基于ElementTree解析器提供了一个更通用,更安全的替代实现(如@stribizhev和@Saket Mittal所述)。
我必须添加一个根元素<Emps>
(以创建一个有效的xml文档,需要根元素),我还选择通过<city>
标记过滤要编辑的位置(但可能是Everyfield):
#!/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
代码的可运行在线版本在这里
以前的正则表达式的实现
这是使用惰性修饰符.*?
的可能实现.*?
并点所有(?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
您可以在此处在线测试代码
注意 :如果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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.