代码之家  ›  专栏  ›  技术社区  ›  Andrei Ciobanu

用python minidom解析文档

  •  0
  • Andrei Ciobanu  · 技术社区  · 14 年前

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

    <?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
    

    作为一个python初学者,你能给我指出问题的根源吗。

    1 回复  |  直到 14 年前
        1
  •  7
  •   chryss    14 年前

    我假设您正在以以下方式传入一个文件句柄:

    >>> 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个数据。我猜文档被解析两次是代码中的一个bug。但是,如果您想这样做,可以用 xmldoc.seek(0) .