Home > Blockchain >  Appending elements into XMl file in Python
Appending elements into XMl file in Python

Time:10-17

I have the following XMl file:

<data>
   
    <Views>
        <view viewname="Request Info" Queryname="Gooo"/>
        <view viewname="To Do" Queryname="For later"/>
    </Views>
</data>

I am trying to add new elements to 'Views' so eventually it will look like this:

    <Views>
        <view viewname="Request Info" Queryname="Gooo"/>
        <view viewname="To Do" Queryname="For later"/>
       <view viewname="Request Info222" Queryname="Gooo"/>
    </Views>
</data>

my code looks like this:

from xml.etree import ElementTree as ET

tree = ET.parse('C:\Python_Projects\Jira_Rest\hest.xml')
root = tree.getroot()

for item in root.findall('Views'):
   
    new = ET.SubElement(item, 'View')
    new.text = '<view viewname="Request Info222" Queryname="Gooo"/>'

there are no errors but the file is not updated with the new data.

CodePudding user response:

See below

import xml.etree.ElementTree as ET

xml = '''<data>
    <Views>
        <view viewname="Request Info" Queryname="Gooo"/>
        <view viewname="To Do" Queryname="For later"/>
    </Views>
</data>'''

root = ET.fromstring(xml)
views = root.find('.//Views')
new_view = ET.Element('view', attrib={'viewname': 'Request Info222', 'Queryname': 'Gooo'})
views.append(new_view)
ET.dump(root)

output

<data>
   <Views>
      <view viewname="Request Info" Queryname="Gooo" />
      <view viewname="To Do" Queryname="For later" />
      <view viewname="Request Info222" Queryname="Gooo" />
   </Views>
</data>
  • Related