pythonxmlminidom

Python minidom check element exists


I have a xml file with this 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 to check if each column exists in the visit tag, and if it does not exist I want to return None, so i wrote this code:

import xml.dom.minidom as minidom
mydict={}
columnsLst=['grade','technology']
doc=minidom.parse('file.xml')
visitcount=len(doc.getElementsByTagName('visit'))
for i in range(visitcount):
   for c in columnsLst:
      if(doc.getElementsByTagName(c)[i].firstChild):
         mydict[c]=doc.getElementsByTagName(c)[i].firstChild.data
   print(mydict)

This does not work, since it does not return None for elements that does not exist. and I get index error since grade does not exist for first visit.

I tried this solution as well to use hasChild() but it gives error:

 'Element' object has no attribute 'hasChild'

Any idea here?


Solution

  • Question: minidom check element exists

    Instead of fideling with Indices use the Resulting NodeLists, for example:

    # Get List of Nodes with Tag <visit>
    visits = doc.getElementsByTagName('visit')
    
    # Iterate NodeList
    for n, visit in enumerate(visits, 1):
        print('{}:{}'.format(n, visit))
    
        # Get SubNodes with Tag <general>
        general = visit.getElementsByTagName('general')
    
        # First Error Condition
        if general:
            # Iterate all Tag Names
            for subtag in ['grade', 'technology']:
                # Second Error Condition, assuming only ONE 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 at 0xf707f52c>
    1:<DOM Element: visit at 0xf6a6125c>
        Missing Subtag <grade>
    2:<DOM Element: visit at 0xf6a6184c>
    

    Tested with Python: 3.4.2