Monday, November 9, 2015

Reading xml file and retrieving data from xml tags using python

Reading xml file and retrieving data from xml tags using python


For below program we need a sample xml file with reference to the sample xml(sample.xml)


from xml.dom import minidom
import sys

def get_values():
    try:
        xmldoc=minidom.parse("sample.xml")                  #----Open and read the xml
     
        to=xmldoc.getElementsByTagName('to')
        for to_val in to:
            rto_val= getText(to_val.childNodes)
            print rto_val
             
        from1=xmldoc.getElementsByTagName('from')
        for from_val in from1:
            rfrom_val= getText(from_val.childNodes)
            print rfrom_val
       
        heading=xmldoc.getElementsByTagName('heading')
        for heading_val in heading:
            rheading_val= getText(heading_val.childNodes)
            print rheading_val
       
        body=xmldoc.getElementsByTagName('body')
        for body_val in body:
            rbody_val= getText(body_val.childNodes)
            print rbody_val
    except IOError as e:                                            #------For IOErrors
        print ("I/O error("+e.errno+"):"+e.strerror+".")
     
    except ValueError:                                              #------ For ValueErrors
        print ("Could not convert data to an integer.")
     
    except:                                                         #----For system errors
        print ("Unexpected error:", sys.exc_info()[0])
     
 
#-------------- Function to get the text between the tags-----------------
def getText(nodelist):
    rc = []
    for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
    return ''.join(rc)

if __name__ == '__main__':
 
    get_values()


here the output will be like this :

Tove
Jani
Reminder

Don't forget me this weekend!



if you find any thing difficulty in understanding feel free to post your comments. I will be glad to assist you with these posts what ever posted in this blog... Thanks for your support.

No comments:

Post a Comment