对于以下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>
这就是我在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"
答案 0 :(得分:1)
您可以查看&#34;键&#34; ==&#39; A&#39; /&#39; B&#39;使用 get 方法,如下所示:
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' ...
答案 1 :(得分:0)
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>