Python XML Parsing without root

前端 未结 3 888
庸人自扰
庸人自扰 2021-02-14 14:33

I wanted to parse a fairly huge xml-like file which doesn\'t have any root element. The format of the file is:




         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-14 15:04

    ElementTree.fromstringlist accepts an iterable (that yields strings).

    Using it with itertools.chain:

    import itertools
    import xml.etree.ElementTree as ET
    # import xml.etree.cElementTree as ET
    
    with open('xml-like-file.xml') as f:
        it = itertools.chain('', f, '')
        root = ET.fromstringlist(it)
    
    # Do something with `root`
    root.find('.//tag3')
    

提交回复
热议问题