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> elementsif node.get('key') == 'Type A':
node.set('value', 'false')
# ... if 'Type B' ...
Solution 2:
- Used
lxml.etree
for parsing HTML content andxpath
method to get targetarg
tag whichkey
attribute value isType 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><Adaptertype="abcdef"><argkey="Type A"value="false"/><argkey="Type B"value="true"/></Adapter></sample>
Post a Comment for "Xml Value Replacement In Python"