如何使用lxml.etree获取第n-1个节点的value值
<test> Node with lxml.etree Got it, let's walk through exactly how to pull the value you need from your XML structure using lxml.etree. Here's a step-by-step breakdown with practical code examples:
Step 1: Import lxml.etree and Parse Your XML
First, make sure you have lxml installed (run pip install lxml if you haven't already). Then parse your XML—whether it's stored as a string or in a file:
Option A: Parse from a string
from lxml import etree # Your XML content as a raw string xml_str = """<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> </test></root>""" root = etree.fromstring(xml_str)
Option B: Parse from a file
from lxml import etree # Load and parse directly from an XML file tree = etree.parse("your_xml_file.xml") root = tree.getroot()
Step 2: Target the (n-1)th <test> Node
Python uses 0-indexing, so the (n-1)th position in the list of <test> nodes maps to the nth logical test node. For example, if you want the 2nd test node, you'll use index 1 (since n=2 → n-1=1):
n = 2 # Replace with your desired n value try: target_test = root.xpath("./test")[n-1] except IndexError: print(f"Error: There is no {n}th <test> node in your XML.") exit()
Step 3: Extract the Value(s)
Now you can pull the value(s) from the targeted <test> node. Here are two common use cases:
Option 1: Get all <value> texts in the target test node
If you want every value under the (n-1)th test:
all_values = [crit.find("value").text for crit in target_test.findall("criteria")] print(f"All values in the {n}th test node: {all_values}") # Output for n=2: All values in the 2nd test node: ['0.655425']
Option 2: Get a specific value by <criteria>'s nom attribute
If you only need the value for a specific criteria (like "DR" or "MOTA"):
# Get value for criteria with nom="DR" dr_value = target_test.xpath('./criteria[@nom="DR"]/value/text()')[0] print(f"DR value in {n}th test node: {dr_value}") # Output for n=2: DR value in 2nd test node: 0.655425
Pro Tip: Add Error Handling
To avoid crashes if the desired criteria doesn't exist in the test node, wrap the lookup in a try-except block:
try: mota_value = target_test.xpath('./criteria[@nom="MOTA"]/value/text()')[0] print(f"MOTA value: {mota_value}") except IndexError: print(f"No MOTA criteria found in the {n}th test node.")
内容的提问来源于stack exchange,提问作者Greg Symsym

