pythonxmlcommentselementtree

Add comment to beginning of document


Using ElementTree, how do I place a comment just below the XML declaration and above the root element?

I have tried root.append(comment), but this places the comment as the last child of root. Can I append the comment to whatever is root's parent?

Thanks.


Solution

  • Here is how a comment can be added in the wanted position (after XML declaration, before root element) with lxml, using the addprevious() method.

    from lxml import etree
    
    root = etree.fromstring('<root><x>y</x></root>')
    comment = etree.Comment('This is a comment')
    root.addprevious(comment)  # Add the comment as a preceding sibling
    
    etree.ElementTree(root).write("out.xml",
                                  pretty_print=True,
                                  encoding="UTF-8",
                                  xml_declaration=True)
    

    Result (out.xml):

    <?xml version='1.0' encoding='UTF-8'?>
    <!--This is a comment-->
    <root>
      <x>y</x>
    </root>