How do I get Python's ElementTree to pretty print to an XML file?

后端 未结 5 1109
猫巷女王i
猫巷女王i 2020-11-28 10:31

Background

I am using SQLite to access a database and retrieve the desired information. I\'m using ElementTree in Python version 2.6 to create an XML file with tha

5条回答
  •  无人及你
    2020-11-28 10:58

    I found a way using straight ElementTree, but it is rather complex.

    ElementTree has functions that edit the text and tail of elements, for example, element.text="text" and element.tail="tail". You have to use these in a specific way to get things to line up, so make sure you know your escape characters.

    As a basic example:

    I have the following file:

    
    
        
            76939
        
        
            266720
            3569
        
    
    

    To place a third element in and keep it pretty, you need the following code:

    addElement = ET.Element("data")             # Make a new element
    addElement.set("version", "3")              # Set the element's attribute
    addElement.tail = "\n"                      # Edit the element's tail
    addElement.text = "\n\t\t"                  # Edit the element's text
    newData = ET.SubElement(addElement, "data") # Make a subelement and attach it to our element
    newData.tail = "\n\t"                       # Edit the subelement's tail
    newData.text = "5431"                       # Edit the subelement's text
    root[-1].tail = "\n\t"                      # Edit the previous element's tail, so that our new element is properly placed
    root.append(addElement)                     # Add the element to the tree.
    

    To indent the internal tags (like the internal data tag), you have to add it to the text of the parent element. If you want to indent anything after an element (usually after subelements), you put it in the tail.

    This code give the following result when you write it to a file:

    
    
        
            76939
        
        
            266720
            3569
         
         
            5431 
         
    
    

    As another note, if you wish to make the program uniformally use \t, you may want to parse the file as a string first, and replace all of the spaces for indentations with \t.

    This code was made in Python3.7, but still works in Python2.7.

提交回复
热议问题