Python XML File Open

后端 未结 1 1053
予麋鹿
予麋鹿 2020-12-18 10:44

I am trying to open an xml file and parse it, but when I try to open it the file never seems to open at all it just keeps running, any ideas?

from xml.dom im         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 11:34

    Running your Python code with a few adjustments:

    from xml.dom import minidom
    Test_file = open('C:/test_file.xml','r')
    xmldoc = minidom.parse(Test_file)
    
    Test_file.close()
    
    def printNode(node):
      print node
      for child in node.childNodes:
           printNode(child)
    
    printNode(xmldoc.documentElement)
    

    With this sample input as test_file.xml:

    
      testing 1
      testing 2
    
    

    Yields this output:

    
    
    
    
    
    
    
    
    

    Notes:

    • As @LukeWoodward mentioned, avoid DOM-based libraries for large inputs, however 180K should be fine. For 180M, control may never return from minidom.parse() without running out of memory first (MemoryError).
    • As @alecxe mentioned, you should eliminate the extraneous ':' in the file spec. You should have seen error output along the lines of IOError: [Errno 22] invalid mode ('r') or filename: 'C::/test_file.xml'.
    • As @mzjn mentioned, xml.dom.minidom.Document is not iterable. You should have seen error output along the lines of TypeError: iteration over non-sequence.

    0 讨论(0)
提交回复
热议问题