Pedro Figueiredo
Pedro Figueiredo

Reputation: 507

How can i add a full new Element (using ElementTree in Python) to a XML File

i have the code posted below, i could add a new Element "continent" to country "Singapore". But i want to add a full Element to the XML File. Is it possible to do that? The "data" variable contains the content of the Element i want to create in the XML File. I tried to append it but... no luck!

My XML File:

<data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>

Here is my Python code:

import xml.etree.ElementTree as et


for item in root.findall("country"):
  if(item.get("name") == "Singapore"):
    new1 = et.Element("continent")
    new1.text = "Asia"
    item.append(new1)
tree.write("countries.xml")


data = '''
  <country name="Portugal">
    <rank updated="yes">21</rank>
    <year>2000</year>
    <gdppc>150000</gdppc>
    <neighbor direction="E" name="Spain" />
  </country>
'''

new2 = et.Element("country")
new2.text = data
root.append(new2)
tree.write("countries.xml")

Upvotes: 1

Views: 117

Answers (1)

mrxra
mrxra

Reputation: 862

try this:

import xml.etree.ElementTree as et

xml = """
<data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>
"""

if __name__ == "__main__":
    tree = et.ElementTree(et.fromstring(xml))
    root = tree.getroot()

    data = '''
      <country name="Portugal">
        <rank updated="yes">21</rank>
        <year>2000</year>
        <gdppc>150000</gdppc>
        <neighbor direction="E" name="Spain" />
      </country>
    '''

    new2 = et.fromstring(data)
    root.append(new2)
    tree.write("countries2.xml")

important is this part, where you generate an xml object hierarchy for your xml snippet (data) and attach it as child to your root node:

new2 = et.fromstring(data)
root.append(new2)

Upvotes: 1

Related Questions