Pretty printing XML in Python

后端 未结 26 2487
一个人的身影
一个人的身影 2020-11-22 02:18

What is the best way (or are the various ways) to pretty print XML in Python?

26条回答
  •  难免孤独
    2020-11-22 02:45

    Use etree.indent and etree.tostring

    import lxml.etree as etree
    
    root = etree.fromstring('

    Welcome

    ') etree.indent(root, space=" ") xml_string = etree.tostring(root, pretty_print=True).decode() print(xml_string)

    output

    
      
      
        

    Welcome


    Removing namespaces and prefixes

    import lxml.etree as etree
    
    
    def dump_xml(element):
        for item in element.getiterator():
            item.tag = etree.QName(item).localname
    
        etree.cleanup_namespaces(element)
        etree.indent(element, space="  ")
        result = etree.tostring(element, pretty_print=True).decode()
        return result
    
    
    root = etree.fromstring('hello world')
    xml_string = dump_xml(root)
    print(xml_string)
    

    output

    
      hello world
    
    

提交回复
热议问题