使用ElementTree获取XML中endTime标签值遇空列表问题求助
endTime Values Hey there! Let's break down why your initial findall("epoch") call returned an empty list, and how to properly grab the specific endTime value you're targeting.
Why Your First Code Failed
The core problem here is XML namespaces. Your XML has a default namespace defined at the root:
<epochs xmlns="http://www.egi.com/epochs_mff" ...>
Every child element (like <epoch>, <endTime>) belongs to this namespace, but xml.etree.ElementTree doesn't automatically recognize it. When you called findall("epoch"), it was looking for elements with no namespace attached—hence the empty result.
Solution: Use Namespace Mapping
To work with namespaced elements cleanly, define a prefix-to-namespace mapping, then use that prefix in your XPath queries.
Step 1: Retrieve All endTime Values
Here's how to properly fetch all endTime values using the namespace:
import xml.etree.ElementTree as ET tree = ET.parse(r'epochs.xml') # Map the namespace to a short prefix (we'll use "egi" here) ns = {'egi': 'http://www.egi.com/epochs_mff'} # Find all <epoch> elements with the namespace prefix epoch_list = tree.findall('.//egi:epoch', ns) # Extract each <endTime> value for epoch in epoch_list: end_time = epoch.find('egi:endTime', ns).text print(end_time)
Step 2: Retrieve a Specific endTime Value
If you're targeting a specific value (like the 300937000 you mentioned), you can either filter results after fetching all epochs or use a precise XPath query:
Option 1: Filter After Fetching All Epochs
target_end_time = "300937000" # Replace with your exact target value for epoch in epoch_list: current_end_time = epoch.find('egi:endTime', ns).text if current_end_time == target_end_time: print(f"Found matching endTime: {current_end_time}") # Grab related values if needed begin_time = epoch.find('egi:beginTime', ns).text print(f"Corresponding beginTime: {begin_time}") break else: print(f"No epoch found with endTime: {target_end_time}")
Option 2: Direct XPath Query for the Target Value
You can skip the full list and directly locate the epoch with your desired endTime using an XPath predicate:
target_end_time = "300937000" # Use XPath to find the epoch where endTime matches your target matching_epoch = tree.find(f'.//egi:epoch[egi:endTime="{target_end_time}"]', ns) if matching_epoch: end_time = matching_epoch.find('egi:endTime', ns).text print(f"Found endTime: {end_time}") else: print(f"No matching endTime found in the XML.")
Why Your Traversal Code Worked
Your recursive loop code worked because it iterates through every element in the tree, ignoring namespace labels. While this gets the job done, it's less efficient and less precise than using namespace-aware queries—especially for larger XML files.
内容的提问来源于stack exchange,提问作者rpb

