Search code examples
pythonxmllibxml2

How to write an xml file using libxml2 in python?


I am attempting to write an xml file in python3 using libxml2. I cannot find any relevant documentation regarding python about writing files with libxml. When I attempt to write an xml file parsed with libxml2 I get the error:

xmlDoc has no attribute write

Anyone here done this before? I can get it to work in Etree just fine but Etree will not respect the attribute order that I need.


Solution

  • You can use saveFile() or saveFileEnc(). Example:

    import libxml2
    
    XML = """
    <root a="1" b="2">XYZ</root>
    """
    
    doc = libxml2.parseDoc(XML)
    
    doc.saveFile("test.xml")
    doc.saveFileEnc("test2.xml", "UTF-8")
    

    I could not find any good documentation for the Python API. Here is the corresponding C documentation: http://xmlsoft.org/html/libxml-tree.html#xmlSaveFile.