Python解析XML数据为字符串而非整数及运行异常问题咨询
Hey Ericka, let's break down your XML parsing issues one by one to get everything sorted out!
First, let's look at your XML structure:
90 7 7
When you run myroot = file_name.getroot(), myroot refers to the root <settings> element. Your code uses for i in myroot[0] — but myroot[0] is the first <standard> element, not the list of all <standard> elements.
The <standard> element only contains text content (like "90") and no child elements. So when you loop over myroot[0], you're trying to iterate over child elements of that single <standard> tag, which don't exist. That's why you get no output.
To fix this, iterate over the direct children of myroot (which are the three <standard> elements):
import xml.etree.ElementTree as ET file_name = ET.parse('imports.xml') myroot = file_name.getroot() # Iterate over all <standard> elements under <settings> for standard in myroot: print(standard.text) # This will output 90, 7, 7
Here's the key thing about XML: it doesn't have built-in data types. Every piece of text inside an element is treated as a string by default, regardless of what it looks like (numbers, dates, etc.).
Python's xml.etree.ElementTree library doesn't automatically convert these strings to integers or other types — it just returns the raw text content. If you need integer values, you'll have to convert them manually using int():
for standard in myroot: value_str = standard.text value_int = int(value_str) # Convert string to integer print(f"String value: {value_str}, Integer value: {value_int}")
Since your code worked one day but broke the next, here are the most likely culprits:
- Missing import statement: If you rewrote the code and forgot to add
import xml.etree.ElementTree as ET, Python won't recognizeETand throw an undefined error. - File path issue: The
imports.xmlfile might have moved, or your script's working directory changed (e.g., you opened the script from a different folder the next day).ET.parse()looks for the file in the current working directory by default. - Typos in code: A small mistake like misspelling
getroot()asgetRoot()(case matters in Python) or using an incorrect variable name could trigger an undefined error.
内容的提问来源于stack exchange,提问作者Ericka

