Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add xml nodes in python using ElementTree

Tags:

python

xml

i have xml file like

<data>
<person>
    <Name>xyz</Name>   
    <add>abc</add>   
</person>
</data>

i want to add another person node like

<data>
<person>
    <Name>xyz</Name>
    <add>abc</add>
</person>
<person>
    <Name>def</Name>
</person>
</data>

my current python code is

import xml.etree.ElementTree as ET   
from xml.etree.ElementTree import Element    
from xml.etree.ElementTree import ElementTree    

root = ET.parse("Lexicon.xml").getroot()    
creRoot = Element("person")

creDictionary = Element("Name")    
creDictionary.text = "def"    
creRoot.append(creDictionary)    
print(ET.tostring(creRoot))   
creTree= ElementTree(creRoot)   
creTree.write("Lexicon.xml")   

when i run this code it will create xml file rather then add and the result is

<person>
    <Name>def</Name>
</person>

and it will remove all previous data.. Kindly anyone who can solve it.. Thanks in advance

like image 740
Mansoor Ahmed Avatar asked Apr 06 '16 09:04

Mansoor Ahmed


2 Answers

SubElement shall be used to add nodes to existing node:

import xml.etree.ElementTree as etree

data = etree.XML(input)
person = etree.SubElement(data, 'person')
name = etree.SubElement(person, 'Name')    
name.text = 'def'    
print(etree.tostring(data))
like image 59
apr Avatar answered Oct 11 '22 16:10

apr


We need to append new create element to respective parent element.

Demo:

>>> import xml.etree.ElementTree as ET 
>>> input_data = """<data>
... <person>
...     <Name>xyz</Name>   
...     <add>abc</add>   
... </person>
... </data>"""
#- Create new Element. 
>>> person_tag = ET.Element("person")
>>> name_tag = ET.Element("Name") 
#- Add text to Element.
>>> name_tag.text = "def"
#- Append Element to Parent Element.
>>> person_tag.append(name_tag)
>>> 
#- Just print Parent Element
>>> ET.tostring(person_tag)
'<person><Name>def</Name></person>'
>>> 
>>> 
#- Created  ET object by formstring.
>>> root = ET.fromstring(input_data)
>>> 
#- Append above element to root element
>>> root.append(person_tag)
#- Print root Element.
>>> print ET.tostring(root)
<data>
<person>
    <Name>xyz</Name>   
    <add>abc</add>   
</person>
<person><Name>def</Name></person></data>
>>> print ET.tostring(root, method="xml")
<data>
<person>
    <Name>xyz</Name>   
    <add>abc</add>   
</person>
<person><Name>def</Name></person></data>
>>> 

Note: Best to use lxml b

like image 39
Vivek Sable Avatar answered Oct 11 '22 16:10

Vivek Sable