Sagar H
Sagar H

Reputation: 141

How to add comment after XML declaration using python

import xml.etree.ElementTree as ET

def addCommentInXml():
    fileXml ='C:\\Users\\Documents\\config.xml'
    tree = ET.parse(fileXml)
    root = tree.getroot()
    comment = ET.Comment('TEST')
    root.insert(1, comment)  # 1 is the index where comment is inserted
    tree.write(fileXml, encoding='UTF-8', xml_declaration=True)
    print("Done")

It is updating xml as below,Please suggest how to add right after xml declaration line:

<?xml version='1.0' encoding='UTF-8'?>
<ScopeConfig Checksum="5846AFCF4E5D02786">
  <ExecutableName>STU</ExecutableName>
  <!--TEST--><ZoomT2Encoder>-2230</ZoomT2Encoder>

Upvotes: 2

Views: 902

Answers (1)

joao
joao

Reputation: 2293

The ElementTree XML API does not allow this. The documentation for the Comment factory function explicitly states:

An ElementTree will only contain comment nodes if they have been inserted into to the tree using one of the Element methods.

but you would like to insert a comment outside the tree. The documentation for the TreeBuilder class is even more explicit:

When insert_comments and/or insert_pis is true, comments/pis will be inserted into the tree if they appear within the root element (but not outside of it)

So I would suggest writing out the XML file without the comment, using this API, and then reading the file as plain text (not parsed XML) to add your comment after the first line.

Upvotes: 1

Related Questions