How to prevent xml.ElementTree fromstring from dropping commentnode

后端 未结 1 598
甜味超标
甜味超标 2020-12-06 01:55

I have tho following code fragment:

    from xml.etree.ElementTree import fromstring,tostring
    mathml = fromstring(input)
    for elem in mathml.getiterat         


        
相关标签:
1条回答
  • 2020-12-06 02:17

    You cannot with xml.etree, because its parser ignores comments (which is acceptable behaviour for an xml parser by the way). But you can if you use the (compatible) lxml library, which allows you to configure parser options.

    from lxml import etree
    
    parser = etree.XMLParser(remove_comments=False)
    tree = etree.parse('input.xml', parser=parser)
    # or alternatively set the parser as default:
    # etree.set_default_parser(parser)
    

    This would by far be the easiest option. If you really have to use xml.etree, you could try hooking up your own parser, although even then, comments are not officially supported: have a look at this example (from the author of xml.etree) (still seems to work in python 2.7 by the way)

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