Python minidom check element exists

Viewed 4868

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?

2 Answers

Yes, I met the same problem, it looks like there is no method to check whether the element is there or not.

You can get the element by name first using getElementsByTagName() and then check the length of the NodeList. For example:

    for xml_txt in test:
        DOMTree = xml.dom.minidom.parseString(xml_txt)
        b = DOMTree.getElementsByTagName('Track')
        if len(b) == 0:
            continue
        else:
            b = b[0]
Related