3
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>
1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.