[英]Get the value from the n-1 node with lxml.etree
我有这个etree:
<root>
<test>
<criteria nom="DR">
<abbr>DR</abbr>
<value>0.123456</value>
</criteria>
<criteria nom="MOTA">
<abbr>MOTA</abbr>
<value>0.132465</value>
</criteria>
<criteria nom="PFR">
<abbr>PFR</abbr>
<value>0.914375</value>
</criteria>
</test>
<test>
<criteria nom="DR">
<abbr>DR</abbr>
<value>0.655425</value>
</criteria>
<criteria nom="MOTA">
<abbr>MOTA</abbr>
<value>0.766545</value>
</criteria>
<criteria nom="PFR">
<abbr>PFR</abbr>
<value>0.943154</value>
</criteria>
</test>
</root>
我需要一个一个的值
0.655425
0.766545
0.943154
以便将它们与值“ 0.25”进行比较。
- 编辑 -
我已经试图通过像这样在主树中循环来获取值:
tree = etree.fromstring(the tree above)
root = tree.getroot()
for test in root.findall("test"):
for criteria in test.findall(criteria):
value = criteria.findall("value").text()
但这不起作用。
使用xml模块 。 并使用enumerate
。
防爆
import xml.etree.ElementTree as ET
tree = ET.fromstring(s)
for i, content in enumerate(tree.findall(".//test")):
if i % 2 != 0:
for val in content.findall("criteria/value"):
print(val.text)
输出:
0.655425
0.766545
0.943154
使用lxml和XPath :
from lxml import etree
tree = etree.parse(open("so.xml"))
for value in tree.xpath("/root/test[2]/criteria/value"):
print(value.text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.