xml - Python minidom check element exists -


i have xml file structure:

<?domparser ?>  <logbook:logbook xmlns:logbook="http://www/logbook/1.0"  version="1.2"> <visits> <visit>     <general>        <technology>eb</technology>     </general> </visit> <visit> <general>     <grade>23242</grade>     <technology>eb</technology> </general> </visit> </visits> </logbook:logbook> 

i want check if each column exists in visit tag, , if not exist want return none, wrote code:

import xml.dom.minidom minidom mydict={} columnslst=['grade','technology'] doc=minidom.parse('file.xml') visitcount=len(doc.getelementsbytagname('visit')) in range(visitcount):    c in columnslst:       if(doc.getelementsbytagname(c)[i].firstchild):          mydict[c]=doc.getelementsbytagname(c)[i].firstchild.data    print(mydict) 

this not work, since not return none elements not exist. , index error since grade not exist first visit.

i tried this solution use haschild() gives error:

 'element' object has no attribute 'haschild' 

any idea here?

question: minidom check element exists

instead of fideling indices use resulting nodelists, example:

# list of nodes tag <visit> visits = doc.getelementsbytagname('visit')  # iterate nodelist n, visit in enumerate(visits, 1):     print('{}:{}'.format(n, visit))      # subnodes tag <general>     general = visit.getelementsbytagname('general')      # first error condition     if general:         # iterate tag names         subtag in ['grade', 'technology']:             # second error condition, assuming 1 subnode <general>             if not general[0].getelementsbytagname(subtag):                 print('\tmissing subtag <{}>'.format(subtag))     else:         print('\tmissing tag <general>') 

output:

<element {http://www/logbook/1.0}logbook @ 0xf707f52c> 1:<dom element: visit @ 0xf6a6125c>     missing subtag <grade> 2:<dom element: visit @ 0xf6a6184c> 

tested python: 3.4.2


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -