用Python解析XML文件XML .dom.minidom



我正在尝试用python解析一个学校项目的XML文件。

为了查看评分是否有效,我打印了"lista_marfur"的值。

显示如下错误:XML .parser .expat. expaterror: XML声明格式不正确:第1行,第35列

XML代码为:

<?xml version="1.0" encoding="UTF-8 standalone="yes"?>
<fapte>
<lista_marfuri>
<marfa> 
<id> 1 </id>
<nume> grebla </nume>
<categorie> gradinarit </gradinarit>
<cantitate> 100 </cantitate>
<pret> 20 </pret>
</marfa>
<marfa> 
<id> 2 </id>
<nume> sac 1kg ingrasamant </nume>
<categorie> gradinarit </gradinarit>
<cantitate> 300 </cantitate>
<pret> 30 </pret>
</marfa>
<marfa> 
<id> 3 </id>
<nume> surubelnita </nume>
<categorie> general </gradinarit>
<cantitate> 200 </cantitate>
<pret> 5 </pret>
</marfa>
</lista_marfuri>


<lista_categorii>
...
</lista_categorii>

<lista_clienti>
...
</lista_clienti>

<lista_comenzi>
...
</lista_comenzi>

</fapte>

python代码是:

import xml.dom.minidom
tree = xml.dom.minidom.parse('SBC.xml')
fapte = tree.documentElement
marfuri = fapte.getElementsByTagName('marfa')
for marfa in marfuri:
print(f"-- Marfa {marfa.getAttribute('id')} --")
nume = marfa.getElementByTagName('nume')[0].childNodes[0].nodeValue
categorie = marfa.getElementByTagName('categorie')[0].childNodes[0].nodeValue
cantitate = marfa.getElementByTagName('cantitate')[0].childNodes[0].nodeValue
pret = marfa.getElementByTagName('pret')[0].childNodes[0].nodeValue
print(f"Nume: {nume}")
print(f"Categorie: {categorie}")
print(f"Cantitate: {cantitate}")
print(f"Pret: {pret}")

我认为使用ElementTree会让你的生活更轻松。

import xml.etree.ElementTree as ET
xml = '''<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>
</fapte>'''
root = ET.fromstring(xml)
for marfa in root.findall('.//marfa'):
for entry in marfa:
print(f'{entry.tag} : {entry.text.strip()}')
print('------------------')

输出
id : 1
nume : grebla
categorie : gradinarit
cantitate : 100
pret : 20
------------------
id : 2
nume : sac 1kg ingrasamant
categorie : gradinarit
cantitate : 300
pret : 30
------------------
id : 3
nume : surubelnita
categorie : general
cantitate : 200
pret : 5
------------------

如果xml是有效的,正确关闭第一行的<categories>的结束标记,如@mzjn所指出的(这也显示了您的错误消息),那么使用pandasread_xml()是最短的:

import pandas as pddf = pd.read_xml('yourFileName.xml', xpath='.//marfa')打印(df) 之前输出:

id编号类别候选pret1 . grebla gradinarit 1001 2袋1公斤,体重300公斤

PS:这只适用于所有感兴趣的值在树中的同一层。