Home > Software design >  Cannot access xml in Python
Cannot access xml in Python

Time:09-23

I´m very new to Python and programming in general and right now I am learning xml processing. The problem is, I can´t write an xml file. I get an "invalid syntax" error because of the first "<" in front of ?xml version="1.0"?> . I am using IDLE 3.9.7, don´t know, if that matters. Sorry, if this is a stupid question, but I´m really clueless here.

<?xml version="1.0"?>
<group>
<person id="1">
<name>John Smith</name>
<age>20</age>
<weight>80</weight>
<height>188</height>
</person>
<person id="2">
<name>Mike Davis</name>
<age>45</age>
<weight>82</weight>
<height>185</height>
</person>
<person id="3">
<name>Anna Johnson</name>
<age>33</age>
<weight>67</weight>
<height>167</height>
</person>
<person id="4">
<name>Bob Smith</name>
<age>60</age>
<weight>70</weight>
<height>174</height>
</person>
<person id="5">
<name>Sarah Pitt</name>
<age>12</age>
<weight>50</weight>
<height>152</height>
</person>
</group>

I want to create a xml file with which i can work with SAX and DOM, as instructed by my learning material.

CodePudding user response:

The code below will generate the XML you have posted. It looks like a good staring point for you.

import xml.etree.ElementTree as ET


data = [{'name': 'jack', 'age': 20, 'weight': 67, 'height': 188},
        {'name': 'sam', 'age': 25, 'weight': 63, 'height': 181}]

group = ET.Element('group')
for idx,entry in enumerate(data,1):
        person = ET.SubElement(group,'person',attrib={'id':str(idx)})
        for k,v in entry.items():
                e = ET.SubElement(person,k)
                e.text = str(v)
ET.dump(group)

output

<?xml version="1.0" encoding="UTF-8"?>
<group>
   <person id="1">
      <name>jack</name>
      <age>20</age>
      <weight>67</weight>
      <height>188</height>
   </person>
   <person id="2">
      <name>sam</name>
      <age>25</age>
      <weight>63</weight>
      <height>181</height>
   </person>
</group>
  • Related