XML<;arg>;Python中的值替换

XML<;arg>;Python中的值替换,python,xml,replace,arguments,Python,Xml,Replace,Arguments,对于下面的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" />

对于下面的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>
您可以使用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' ...
用于tree.iterfind('.//logging/Adapter[@type=“abcdef”]/arg')中的节点:
#因此,您不需要另一个内部循环来访问元素
如果node.get('key')=='Type A':
node.set('value','false')
# ... 如果“类型B”。。。
  • 使用
    lxml.etree
    解析HTML内容和
    xpath
    方法获取
    arg
    标记,该标记的
    属性值为
    类型A
  • 代码:

    输出:

    python test.py 
    <sample>
        <Adapter type="abcdef">
            <arg key="Type A" value="false"/>
            <arg key="Type B" value="true"/>
        </Adapter>
    </sample>
    
    python test.py
    
    我告诉过你你很棒吗?
    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>