Skip to content Skip to sidebar Skip to footer

XML Value Replacement In Python

For the following sample.xml file, how do I replace the value of arg key 'Type A' and 'Type B' separately using Python? sample.xml:

Solution 1:

You can check the "key" == 'Type A' / 'Type B' by using get method, like this:

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' ...

In fact, you can improve your code by using a better xpath accessing directly:

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' ...

Solution 2:

  1. Used lxml.etree for parsing HTML content and xpath method to get target arg tag which key attribute value is Type A

Code:

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)

Output:

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

Post a Comment for "XML Value Replacement In Python"