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

使用Python xml.dom.minidom解析XML遇ExpatError错误求助

解决XML解析错误及Python代码问题

XML文件的问题修正

你的XML文件存在两处关键错误,直接导致解析失败:

  • XML声明格式错误:原声明中encoding与standalone参数的语法不符合规范,正确格式需用双引号分隔每个参数,且参数间添加空格。
  • 标签不匹配:所有<categorie>标签的闭合标签错误写成了<gradinarit>,XML要求起始标签与闭合标签名称必须完全一致。

修正后的XML代码:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<fapte>
    <lista_marfuri>
        <marfa> 
            <id> 1 </id>
            <nume> grebla </nume>
            <categorie> gradinarit </categorie>
            <cantitate> 100 </cantitate>
            <pret> 20 </pret>
        </marfa>
        <marfa> 
            <id> 2 </id>
            <nume> sac 1kg ingrasamant </nume>
            <categorie> gradinarit </categorie>
            <cantitate> 300 </cantitate>
            <pret> 30 </pret>
        </marfa>
        <marfa> 
            <id> 3 </id>
            <nume> surubelnita </nume>
            <categorie> general </categorie>
            <cantitate> 200 </cantitate>
            <pret> 5 </pret>
        </marfa>
    </lista_marfuri>
    
    
    <lista_categorii>
        ...
    </lista_categorii>
    
    <lista_clienti>
        ...
    </lista_clienti>
    
    <lista_comenzi>
        ...
    </lista_comenzi>
    
</fapte>

Python代码的问题修正

你的Python代码存在三处逻辑与语法错误:

  • 方法名拼写错误:getElementByTagName应为复数形式getElementsByTagName(DOM标准方法为复数)。
  • id值获取方式错误:XML中id是<marfa>的子标签而非属性,不能用getAttribute获取,需通过子标签抽取文本值。
  • 文本冗余空格处理:直接获取nodeValue会包含标签内的空白字符,需用strip()清理前后空格。

修正后的Python代码:

import xml.dom.minidom

tree = xml.dom.minidom.parse('SBC.xml')

fapte = tree.documentElement

marfuri = fapte.getElementsByTagName('marfa')

for marfa in marfuri:
    # 获取id子标签的文本值并清理空格
    id_val = marfa.getElementsByTagName('id')[0].childNodes[0].nodeValue.strip()
    print(f"-- Marfa {id_val} --")

    nume = marfa.getElementsByTagName('nume')[0].childNodes[0].nodeValue.strip()
    categorie = marfa.getElementsByTagName('categorie')[0].childNodes[0].nodeValue.strip()
    cantitate = marfa.getElementsByTagName('cantitate')[0].childNodes[0].nodeValue.strip()
    pret = marfa.getElementsByTagName('pret')[0].childNodes[0].nodeValue.strip()

    print(f"Nume: {nume}")
    print(f"Categorie: {categorie}")
    print(f"Cantitate: {cantitate}")
    print(f"Pret: {pret}")

内容的提问来源于stack exchange,提问作者Hi I'm Irish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:15:35