Python解析XML:提取企业级软件XML中item节点的整数值
嘿,我来帮你搞定从XML里提取<item>节点整数值的需求!下面分两种场景给你写代码,适配你当前的Python 2.7,也给你升级到最新版后的推荐写法。
Python 2.7 适配方案
因为你现在还在用Python 2.7,咱们用标准库自带的xml.etree.ElementTree来处理,不用额外装包,稳得很:
import xml.etree.ElementTree as ET # 补全你截断的XML内容,实际使用时替换成真实的XML字符串或文件路径 xml_content = '''<counters> <item name="stats/counters/session/responsetime" type="int">1047</item> <item name="stats/counters/session/responsecount" type="int">7423</item> <item name="stats/counters/init/inittime" type="int">36339</item> <item name="stats/counters/other/active" type="int">89</item> </counters>''' # 解析XML字符串 root = ET.fromstring(xml_content) # 遍历所有<item>节点,提取有效整数值 int_values = [] for item in root.findall('item'): # 只处理type标记为int的节点,避免非整数内容 if item.get('type') == 'int': try: value = int(item.text.strip()) int_values.append(value) # 可以同时输出统计项名称,方便对应数据 print(f"统计项 [{item.get('name')}]: {value}") except ValueError: print(f"警告:节点 [{item.get('name')}] 的内容不是有效整数") print("\n提取到的所有整数值:", int_values)
Python 3+ 推荐方案
要是你升级到最新版Python(比如3.10+),写法会更简洁清爽,而且ElementTree的API基本兼容,还能用上现代语法:
import xml.etree.ElementTree as ET # 如果XML是文件,直接用parse方法读取更方便 # tree = ET.parse('your_counters.xml') # root = tree.getroot() # 用字符串解析的示例(替换成真实内容即可) xml_content = '''<counters> <item name="stats/counters/session/responsetime" type="int">1047</item> <item name="stats/counters/session/responsecount" type="int">7423</item> <item name="stats/counters/init/inittime" type="int">36339</item> <item name="stats/counters/other/active" type="int">89</item> </counters>''' root = ET.fromstring(xml_content) # 用列表推导式简化提取逻辑,同时过滤无效内容 int_values = [ int(item.text.strip()) for item in root.findall('item') if item.get('type') == 'int' and item.text.strip().isdigit() ] # 如果需要统计项和数值的对应关系,生成字典更实用 stats_map = { item.get('name'): int(item.text.strip()) for item in root.findall('item') if item.get('type') == 'int' and item.text.strip().isdigit() } print("提取到的整数值列表:", int_values) print("统计项-数值对应表:", stats_map)
小提醒
- 我特意加了
type="int"的判断,防止误提取其他类型的<item>节点(比如可能存在的字符串类型节点) - 加了内容有效性检查,避免XML里的空内容或非数字字符串导致程序报错
- 如果你的XML是从本地文件读取的,直接用
ET.parse()方法比字符串解析更高效
内容的提问来源于stack exchange,提问作者user2611207
相关产品推荐
相关产品推荐

