KAz
KAz

Reputation: 5

Add child of child to python xml

I create a code which writes the data to xml file.But it is not working properly. It gives a error called "TypeError: must be Element, not None "

Here is my code:

import xml.etree.cElementTree as ET
import lxml.etree
import lxml.builder

class create_xml:
  def __init__(self):
      pass


def write_xml(predicted_list, image_list):

   print predicted_list
   print image_list
   i = 0
   root = ET.Element("video_data")

   for image in image_list:
     doc = ET.SubElement(root, 'frame').set('name', image)
     predicted_item = predicted_list[i]
     ET.SubElement(doc, predicted_item) **Gives error in here**
     # doc.text = predicted_list[i]
     i += 1

 tree = ET.ElementTree(root)
 tree.write("/opt/lampp/htdocs/video_frames/test.xml")

I need the out put as below,

<video_data>
  <frame name="">
   <predicted_item>output</predicted_item>
  </frame>
</video_data>

But without the error occuring code segment it gives the output as below:

 <video_data><frame name="/opt/lampp/htdocs/video_frames/bb/frame48.jpg" /></video_data>

please help me to solve this, Thank you

Upvotes: 0

Views: 179

Answers (1)

alecxe
alecxe

Reputation: 473853

The problem is that doc becomes None since it equals to the result of set() call. Instead, you meant to have doc pointing to the SubElement instance:

doc = ET.SubElement(root, 'frame')
doc.set('name', image)

Upvotes: 1

Related Questions