对于以下sample.xml中的文件,我怎么更换ARG关键的“A类”和“B型”分别使用Python的价值?
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方法,这样检查的“钥匙” ==“A型” /“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' ...
- 二手
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>