Hi guys,

I need your help as I got stuck. I'm trying to fetch the data from my own xml which it looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
  <channel id='101 ABC FAMILY'>
    <display-name>101 ABC FAMILY </display-name>
  <programme channel="101 ABC FAMILY" start="20140520110000" stop="20140520120000">
    <title lang="en">Gilmore Girls -  Let the Games Begin</title>
    <sub-title lang="en"> </sub-title>
    <desc lang="en"> </desc>
    <category lang="en"> </category>
  </programme>
  <programme channel="101 ABC FAMILY" start="20140520120000" stop="20140520123000">
    <title lang="en">8 Simple Rules -  Thanksgiving Guest</title>
    <sub-title lang="en"> </sub-title>
    <desc lang="en"> </desc>
    <category lang="en"> </category>
  </programme>
  <programme channel="101 ABC FAMILY" start="20140520123000" stop="20140520130000">
    <title lang="en">8 Simple Rules -  Vanity Unfair</title>
    <sub-title lang="en"> </sub-title>
    <desc lang="en"> </desc>
    <category lang="en"> </category>
  </programme>
  <programme channel="101 ABC FAMILY" start="20140520130000" stop="20140520133000">
    <title lang="en">Reba -  Seeing Red</title>
    <sub-title lang="en"> </sub-title>
    <desc lang="en"> </desc>
    <category lang="en"> </category>
  </programme>
  <programme channel="101 ABC FAMILY" start="20140520133000" stop="20140520140000">
    <title lang="en">Reba -  Terry Holliway</title>
    <sub-title lang="en"> </sub-title>
    <desc lang="en"> </desc>
    <category lang="en"> </category>
  </programme>
 </channel>

Here is my code:

import xbmc
import xbmcgui
import xbmcaddon
import os
import urllib2
import StringIO
import sqlite3
from sqlite3 import dbapi2 as database
from xml.etree import ElementTree
from UserDict import DictMixin
import datetime
import time

#get actioncodes from keyboard.xml
ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_UP = 3
ACTION_MOVE_DOWN = 4
ACTION_ENTER = 7
ACTION_PREVIOUS_MENU = 10
ACTION_BACKSPACE = 110
def cSetVisible(WiNdOw,iD,V=True): WiNdOw.getControl(iD).setVisible(V)
ADDON = xbmcaddon.Addon(id = 'script.tvguide')


class Channel:
     def __init__(self):
         self.__display_name = None
         self.__icon = None
         self.__programs = []


     def get_display_name(self):
         return self.__display_name


     def get_icon(self):
         return self.__icon


     def get_programs(self):
         return self.__programs



     def set_display_name(self, value):
         self.__display_name = value


     def set_icon(self, value):
         self.__icon = value


     def set_programs(self, value):
         self.__programs = value


     def del_display_name(self):
         del self.__display_name


     def del_icon(self):
         del self.__icon


     def del_programs(self):
         del self.__programs

     display_name = property(get_display_name, set_display_name, del_display_name, "display_name's docstring")
     icon = property(get_icon, set_icon, del_icon, "icon's docstring")
     programs = property(get_programs, set_programs, del_programs, "programs's docstring")




class Programme:
     def __init__(self):
         self.__start = None
         self.__stop = None
         self.__title = None
         self.__sub_title = None
         self.__desc = None
         self.__category = []
         self.__credits = []
         self.__icon = None
         self.__episode_num = None

     def get_episode_num(self):
         return self.__episode_num


     def set_episode_num(self, value):
         self.__episode_num = value


     def del_episode_num(self):
         del self.__episode_num


     def get_start(self):
         return self.__start


     def get_stop(self):
         return self.__stop


     def get_title(self):
         return self.__title


     def get_sub_title(self):
         return self.__sub_title


     def get_desc(self):
         return self.__desc


     def get_category(self):
         return self.__category


     def get_credits(self):
         return self.__credits


     def get_icon(self):
         return self.__icon


     def set_start(self, value):
         self.__start = value


     def set_stop(self, value):
         self.__stop = value


     def set_title(self, value):
         self.__title = value


     def set_sub_title(self, value):
         self.__sub_title = value


     def set_desc(self, value):
         self.__desc = value


     def set_category(self, value):
         self.__category = value


     def set_credits(self, value):
         self.__credits = value


     def set_icon(self, value):
         self.__icon = value


     def del_start(self):
         del self.__start


     def del_stop(self):
         del self.__stop


     def del_title(self):
         del self.__title


     def del_sub_title(self):
         del self.__sub_title


     def del_desc(self):
         del self.__desc


     def del_category(self):
         del self.__category


     def del_credits(self):
         del self.__credits


     def del_icon(self):
         del self.__icon

     start = property(get_start, set_start, del_start, "start's docstring")
     stop = property(get_stop, set_stop, del_stop, "stop's docstring")
     title = property(get_title, set_title, del_title, "title's docstring")
     sub_title = property(get_sub_title, set_sub_title, del_sub_title, "sub_title's docstring")
     desc = property(get_desc, set_desc, del_desc, "desc's docstring")
     category = property(get_category, set_category, del_category, "category's docstring")
     creditss = property(get_credits, set_credits, del_credits, "credits's docstring")
     icon = property(get_icon, set_icon, del_icon, "icon's docstring")
     episode_num = property(get_episode_num, set_episode_num, del_episode_num, "episode_num's docstring")



class Credits:
     def __init__(self):
         self.__type = None
         self.__role = None
         self.__name = None

     def get_type(self):
         return self.__type


     def get_role(self):
         return self.__role


     def get_name(self):
         return self.__name


     def set_type(self, value):
         self.__type = value


     def set_role(self, value):
         self.__role = value


     def set_name(self, value):
         self.__name = value


     def del_type(self):
         del self.__type


     def del_role(self):
         del self.__role


     def del_name(self):
         del self.__name

     type = property(get_type, set_type, del_type, "type's docstring")
     role = property(get_role, set_role, del_role, "role's docstring")
     name = property(get_name, set_name, del_name, "name's docstring")




class OrderedDict(dict, DictMixin):

    def __init__(self, *args, **kwds):
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__end
        except AttributeError:
            self.clear()
        self.update(*args, **kwds)

    def clear(self):
        self.__end = end = []
        end += [None, end, end]         # sentinel node for doubly linked list
        self.__map = {}                 # key --> [key, prev, next]
        dict.clear(self)

    def __setitem__(self, key, value):
        if key not in self:
            end = self.__end
            curr = end[1]
            curr[2] = end[1] = self.__map[key] = [key, curr, end]
        dict.__setitem__(self, key, value)

    def __delitem__(self, key):
        dict.__delitem__(self, key)
        key, prev, next = self.__map.pop(key)
        prev[2] = next
        next[1] = prev

    def __iter__(self):
        end = self.__end
        curr = end[2]
        while curr is not end:
            yield curr[0]
            curr = curr[2]

    def __reversed__(self):
        end = self.__end
        curr = end[1]
        while curr is not end:
            yield curr[0]
            curr = curr[1]

    def popitem(self, last=True):
        if not self:
            raise KeyError('dictionary is empty')
        if last:
            key = reversed(self).next()
        else:
            key = iter(self).next()
        value = self.pop(key)
        return key, value

    def __reduce__(self):
        items = [[k, self[k]] for k in self]
        tmp = self.__map, self.__end
        del self.__map, self.__end
        inst_dict = vars(self).copy()
        self.__map, self.__end = tmp
        if inst_dict:
            return (self.__class__, (items,), inst_dict)
        return self.__class__, (items,)

    def keys(self):
        return list(self)

    setdefault = DictMixin.setdefault
    update = DictMixin.update
    pop = DictMixin.pop
    values = DictMixin.values
    items = DictMixin.items
    iterkeys = DictMixin.iterkeys
    itervalues = DictMixin.itervalues
    iteritems = DictMixin.iteritems

    def __repr__(self):
        if not self:
            return '%s()' % (self.__class__.__name__,)
        return '%s(%r)' % (self.__class__.__name__, self.items())

    def copy(self):
        return self.__class__(self)

    @classmethod
    def fromkeys(cls, iterable, value=None):
        d = cls()
        for key in iterable:
            d[key] = value
        return d

    def __eq__(self, other):
        if isinstance(other, OrderedDict):
            if len(self) != len(other):
                return False
            for p, q in  zip(self.items(), other.items()):
                if p != q:
                    return False
            return True
        return dict.__eq__(self, other)

    def __ne__(self, other):
        return not self == other


class MyClass(xbmcgui.WindowXML):

ef __new__(cls):
         return super(MyClass, cls).__new__(cls, 'script-tvguide-mainmenu.xml', ADDON.getAddonInfo('path'))


    def load_channel(self, elem):
         channel = Channel()
         for elem in elem.getchildren():
             if elem.tag == 'display-name':
                 channel.set_display_name(elem.text)
             elif elem.tag == 'icon':
                 channel.set_icon(elem.attrib['src'])
         return channel



     def load_programme(self, elem):
         programme = Programme()
         programme.set_start(elem.attrib['start'])
         programme.set_stop(elem.attrib['stop'])

         for elem in elem.getchildren():
             if elem.tag == 'title':
                 programme.set_title(elem.text)
             elif elem.tag == 'sub-title':
                 programme.set_title(elem.text)
             elif elem.tag == 'desc':
                 programme.set_desc(elem.text)
             elif elem.tag == 'category':
                 categories = programme.get_category()
                 categories.append(elem.text)
             elif elem.tag == 'episode-num':
                 programme.set_episode_num(elem.text)
             elif elem.tag == 'credits':
                 creditss = programme.get_credits()
                 creditss.append(self.load_credits(elem))
             elif elem.tag == 'icon':
                 programme.set_icon(elem.attrib['src'])
         return programme



     def load_credits(self, elem):
         creditss = Credits()
         for elem in elem.getchildren():
             if elem.tag == 'actor':
                 creditss.set_name(elem.text)
                 creditss.set_type('actor')
             elif elem.tag == 'presenter':
                 creditss.set_name(elem.text)
                 creditss.set_type('presenter')
             elif elem.tag == 'director':
                 creditss.set_name(elem.text)
                 creditss.set_type('director')
         return credits



     def onAction(self, action):
          if action == ACTION_ENTER:
             if tvguide_yellow:
                 if allchannels_yellow:
                     ADDON.setSetting('allchannels.enabled', 'true')
                     server_test = ADDON.getSetting('ontv.url')
                     cSetVisible(self,4200,True)

                     #DOWNLOAD THE XML SOURCE HERE
                     url = ADDON.getSetting('allchannels.url')
                     req = urllib2.Request(url)
                     response = urllib2.urlopen(req)
                     data = response.read()
                     response.close()
                     profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', ''))

                     if os.path.exists(profilePath):
                         profilePath = profilePath + 'source.db'
                         con = database.connect(profilePath)
                         cur = con.cursor()
                         cur.execute('CREATE TABLE programs(id TEXT, channel TEXT, title TEXT, start_date TIMESTAMP, end_date TIMESTAMP, description TEXT)')
                         con.commit()
                         con.close
                         tv_elem = ElementTree.parse(StringIO.StringIO(data)).getroot()

                         profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', ''))
                         profilePath = profilePath + 'source.db'
                         con = database.connect(profilePath)
                         cur = con.cursor()
                         channels = OrderedDict()

                         for elem in tv_elem.getchildren():
                             if elem.tag == 'channel':
                                 channels[elem.attrib['id']] = self.load_channel(elem)
                             elif elem.tag == 'programme':
                                 # get channel
                                 channel = channels[elem.attrib['programme']]
                                 channel = channels[elem.attrib['title']]
                                 # load program in channel
                                 channel.get_programs().append(self.load_programme(elem))
                         for channel_key in channels:
                             channel = channels[channel_key]
                             display_name = channel.get_display_name()
                             title = channel.get_programs()
                             print channel.get_display_name()
                             print channel.get_programs()

Here is the logs:

17:26:46 T:2044  NOTICE: 101 ABC FAMILY
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 102 CBS
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 103 CNN USA
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 105 ESPN USA
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 106 Fox News
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 107 Animal Planet
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 108 USA Network
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 110 SPIKE
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 111 BRAVO USA
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 112 BRAVO1
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 113 BRAVO2
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 114 BRAVO3
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 115 BRAVO4
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 116 BRAVO5
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 117 BRAVO6
17:26:46 T:2044  NOTICE: []
17:26:46 T:2044  NOTICE: 118 BRAVO7
17:26:46 T:2044  NOTICE: []

I want to fetch the list of programme title, but I have got no idea how to fetch them and print them in the xml log. Do you know how?

And I'm trying to find out how I can use the start and stop format to work for each programme, but I have got no idea how it works. Can you please help with this?

Any advise would be much appreicated.

Thanks in advance

I would go with BeautifulSoup as it produces short code, for example

# -*-coding: utf8-*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from BeautifulSoup   import BeautifulSoup

def main():
    filename = 'input.xml'
    soup = BeautifulSoup(open(filename).read())
    for channel in soup.findAll('channel'):
        cid = channel['id'] # or dict(channel.attrs)['id']
        for prog in channel.findAll('programme'):
            for title in prog.findAll('title'):
                print(cid, ':', title.text)


if __name__ == '__main__':
    main()

""" my output -->

101 ABC FAMILY : Gilmore Girls - Let the Games Begin
101 ABC FAMILY : 8 Simple Rules - Thanksgiving Guest
101 ABC FAMILY : 8 Simple Rules - Vanity Unfair
101 ABC FAMILY : Reba - Seeing Red
101 ABC FAMILY : Reba - Terry Holliway
102 CBS : Local Programming
102 CBS : The Price Is Right
102 CBS : Local Programming
102 CBS : The Young and the Restless
102 CBS : The Bold and the Beautiful
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.