XML<;arg>;Python中的值替换
对于下面的sample.xml文件,如何使用Python分别替换arg键“Type A”和“Type B”的值 sample.xml:XML<;arg>;Python中的值替换,python,xml,replace,arguments,Python,Xml,Replace,Arguments,对于下面的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" />
<sample>
<Adapter type="abcdef">
<arg key="Type A" value="true" />
<arg key="Type B" value="true" />
</Adapter>
</sample>
您可以使用get方法检查“key”==“Type A”/“Type 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' ...
用于tree.iterfind('.//logging/Adapter[@type=“abcdef”]/arg')中的节点:
#因此,您不需要另一个内部循环来访问元素
如果node.get('key')=='Type A':
node.set('value','false')
# ... 如果“类型B”。。。
lxml.etree
解析HTML内容和xpath
方法获取arg
标记,该标记的键
属性值为类型A
python test.py
<sample>
<Adapter type="abcdef">
<arg key="Type A" value="false"/>
<arg key="Type B" value="true"/>
</Adapter>
</sample>
python test.py
我告诉过你你很棒吗?
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>