XML <arg> 中的值替换 Python

XML <arg> value Replacement in Python

对于以下 sample.xml 文件,如何使用 Python 分别替换 arg 键 "Type A" 和 "Type B" 的值?

sample.xml:

        <sample>
            <Adapter type="abcdef">
                <arg key="Type A" value="true" />
                <arg key="Type B" value="true" />
            </Adapter>
        </sample>

这是我在 Python 中处理 arg 属性的方式:

tree = ET.parse('sample.xml')
for node in tree.iterfind('.//logging/Adapter[@type="abcdef"]'):
    for child in node:
        child.set('value', 'false') #This change both values to "false"

您可以使用 get 方法检查 "key" == 'Type A' / 'Type B',如下所示:

for node in tree.iterfind('.//logging/Adapter[@type="abcdef"]'):
    for child in node:
        # check if the key is 'Type A'
        if child.get('key') == 'Type A':
            child.set('value', 'false')
        # ... if 'Type B' ...

实际上,您可以通过使用更好的 xpath 直接访问来改进您的代码:

for node in tree.iterfind('.//logging/Adapter[@type="abcdef"]/arg'):
    # so you don't need another inner loop to access <arg> elements
    if node.get('key') == 'Type A':
        node.set('value', 'false')
    # ... if 'Type B' ...
  1. 使用lxml.etree解析HTML内容和xpath方法获取目标arg标签,key属性值为Type A

代码:

from lxml import etree
root = etree.fromstring(content)
for i in root.xpath('//Adapter[@type="abcdef"]/arg[@key="Type A"]'):
    i.attrib["value"] = "false"

print etree.tostring(root)

输出:

python test.py 
<sample>
    <Adapter type="abcdef">
        <arg key="Type A" value="false"/>
        <arg key="Type B" value="true"/>
    </Adapter>
</sample>