Search code examples
pythonxmlminidom

Python minidom Trouble obtaining value of child node


I've read several answers on here regarding this question and am still unable to solve it.

Basically, I want to print the nodeValue of a child node.

Here is the xml:

 <issues>
   <maxResultsReached>true</maxResultsReached>
   <paging>
     <pageIndex>2</pageIndex>
     <pageSize>500</pageSize>
     <total>10000</total>
     <fTotal>10,000</fTotal>
     <pages>20</pages>
   </paging>
 <issues>

I am trying to get the nodeValue of "total".

Here is what I wrote:

totalIssues = dom.getElementsByTagName('issues')[0].childNodes[1].childNodes[2]

I have experimented by so far the only results I got where either None or blank space.

Also, how can I get a childNode simply by name? Since many times, there will be another element present which will shift the position of "total" element.


Solution

  • Get it in several steps and be explicit about tag names:

    issue = dom.getElementsByTagName('issues')[0]
    paging = issue.getElementsByTagName('paging')[0]
    total = paging.getElementsByTagName('total')[0]
    print total.firstChild.nodeValue   # prints 10000
    

    Just FYI, you see it is not fun to use minidom for xml parsing? Ok, here is an alternative using xml.etree.ElementTree from the standard library:

    issues = ET.fromstring(data)
    total = issues.find('./paging/total')
    print total.text  # prints 10000
    

    where data is your XML string.

    Hope that helps.