You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解析XML数据为字符串而非整数及运行异常问题咨询

Hey Ericka, let's break down your XML parsing issues one by one to get everything sorted out!


1. Why your loop doesn't return any output

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

2. Why XML "integer" data is parsed as a string

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}")

3. Possible causes for the "undefined error" you saw earlier

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 recognize ET and throw an undefined error.
  • File path issue: The imports.xml file 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() as getRoot() (case matters in Python) or using an incorrect variable name could trigger an undefined error.

内容的提问来源于stack exchange,提问作者Ericka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:52:30