用python minidom解析文档

2024-05-12 23:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下XML文档,必须使用python的minidom进行解析:

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

<root>
    <bash-function activated="True">
        <name>lsal</name>
        <description>List directory content (-al)</description>
        <code>ls -al</code>
    </bash-function>

    <bash-function activated="True">
        <name>lsl</name>
        <description>List directory content (-l)</description>
        <code>ls -l</code>
    </bash-function>
</root>

下面是我试图解析的代码(基本部分):

from modules import BashFunction
from xml.dom.minidom import parse

class FuncDoc(object):
    def __init__(self, xml_file):
        self.active_func = []
        self.inactive_func = []
        try:
            self.dom = parse(xml_file)
        except Exception as inst:
            print type(inst)
            print inst.args
            print inst

不幸的是我遇到了一些错误。这是stacktrace:

<class 'xml.parsers.expat.ExpatError'>
('no element found: line 1, column 0',)
no element found: line 1, column 0

作为一个python初学者,你能告诉我问题的根源吗。


Tags: nameselfbashtruecodefunctionrootdescription
1条回答
网友
1楼 · 发布于 2024-05-12 23:25:00

我想您是通过以下方式传入一个文件句柄:

>>> from xml.dom.minidom import parse
>>> xmldoc = open("xmltestfile.xml", "rU")
>>> x = FuncDoc(xmldoc)

如果我尝试分析同一个文档两次而不在两次之间关闭它,那么我将得到与您相同的错误。试试这个——错误出现在第二次分析尝试之后:

>>> xmldoc.close()
>>> xmldoc = open("xmltestfile.xml", "rU")
>>> xml1 = parse(xmldoc)
>>> xml2 = parse(xmldoc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/dom/minidom.py", line 1918, in parse
    return expatbuilder.parse(file)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/dom/expatbuilder.py", line 928, in parse
    result = builder.parseFile(file)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/dom/expatbuilder.py", line 211, in parseFile
    parser.Parse("", True)
xml.parsers.expat.ExpatError: no element found: line 1, column 0

在第一次解析之后,整个文件已经被读取。然后,新的分析尝试接收0个数据。我猜文档被解析两次是代码中的一个错误。但是,如果您想这样做,可以使用xmldoc.seek(0)重置它。

相关问题 更多 >