Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'lxml.etree._ElementTree' object has no attribute 'insert'

I am trying to parse through my .xml file using glob and then use etree to add more code to my .xml. However, I keep getting an error when using doc insert that says object has no attribute insert. Does anyone know how I can effectively add code to my .xml?

from lxml import etree
path = "D:/Test/"
for xml_file in glob.glob(path + '/*/*.xml'):
    doc = etree.parse(xml_file)
    new_elem = etree.fromstring("""<new_code abortExpression=""
                        elseExpression=""
                        errorIfNoMatch="false"/>""")
doc.insert(1,new_elem)
new_elem.tail = "\n"

My original xml looks like this :

<data>
  <assesslet index="Test" hash-uptodate="False" types="TriggerRuleType" verbose="True"/>
</data>

And I’d like to modify it to look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<data>
<assesslet index="Test" hash-uptodate="False" types="TriggerRuleType" verbose="True"/>
<new_code abortExpression="" elseExpression="" errorIfNoMatch="false"/>
</data>

>Solution :

The problem is that you need to extract the root from your document before you can start modifying it: modify doc.getroot() instead of doc.

This works for me:

from lxml import etree
xml_file = "./doc.xml"
doc = etree.parse(xml_file)
new_elem = etree.fromstring("""<new_code abortExpression=""
                            elseExpression=""
                            errorIfNoMatch="false"/>""")
root = doc.getroot()
root.insert(1, new_elem)
new_elem.tail="\n"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading