使用python替换xml标记内容

2024-07-07 06:10:21 发布

您现在位置: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语言构造了带有修正值的位置信息。在

^{pr2}$

因此,应该用新的信息替换位置标签。在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>

有什么想法吗??在

谢谢。在


Tags: 文件数据name信息citytypelocationxml
1条回答
网友
1楼 · 发布于 2024-07-07 06:10:21

UPDATE-XML解析器实现:由于替换一个特定的<Location>标记需要修改regex,所以我提供了一个基于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的联机可运行版本

以前的REGEX实现

这是使用lazy修饰符.*?和dot all (?s)的可能实现:

^{pr2}$

您可以在线测试代码here

警告:如果xml输入中有多个<Location>标记,则regex将它们全部替换为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)

相关问题 更多 >