How do I get properly escaped XML in python etree untouched?

前端 未结 1 1373
北海茫月
北海茫月 2021-01-19 02:28

I\'m using python version 2.7.3.

test.txt:



    The tag &am         


        
相关标签:
1条回答
  • 2021-01-19 03:00
    import xml.etree.ElementTree as ET
    e = ET.parse('test.txt')
    root = e.getroot()
    print(ET.tostring(root.find('test')))
    

    yields

    <test>The tag &lt;StackOverflow&gt; is good to bring up at parties.</test>
    

    Alternatively, you could escape the text with saxutils.escape:

    import xml.sax.saxutils as saxutils
    print(saxutils.escape(root.find('test').text))
    

    yields

    The tag &lt;StackOverflow&gt; is good to bring up at parties.
    
    0 讨论(0)
提交回复
热议问题