1

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:

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

This is how I approach to the arg attribute in Python:

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"
0

2 Answers 2

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' ...
Sign up to request clarification or add additional context in comments.

1 Comment

Did I tell you you are awesome?
0
  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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.