与Python的minidom解析文档
我有,我有使用Python的minidom命名解析下面的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
不幸的是我遇到了一些错误。这里是栈跟踪:
<class 'xml.parsers.expat.ExpatError'>
('no element found: line 1, column 0',)
no element found: line 1, column 0
作为一个蟒蛇初学者,请你指点我的问题的根源。
我想你传递一个文件句柄,以下列方式:
>>> 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)
进行重置。
要将文件光标恢复到开始位置,请使用'xmldoc.seek(0)'。 – katrielalex 2010-09-02 13:16:13
谢谢,好主意添加这个,我做了。 – chryss 2010-09-02 15:55:08
感谢您的回答。问题是我不应该关闭()文件对象。 – 2010-09-02 16:34:21
你怎么称呼FuncDoc?这个例子实际上对我很好(至少没有例外) – 2010-09-02 10:03:13
-1因为我没有提供信息 – 2010-09-02 11:13:40
@Ivan van der Wijk,可能是因为我在电脑前24/24。我也没有考虑这方面的重要。我想我调用FuncDom的Constructor非常合乎逻辑。 – 2010-09-02 15:40:34