pythonxmlparsingelementtreexml.etree

Get value from XML in python using xml etree


I'm trying to get a value from a xml string but it's throwing attrib can't be retrieved from None type.

Consider below XML

<summary-report>
  <static-analysis>
    <modules>
     <module sev0issue="0" sev1issue="14">
     </module>
    </modules>
</static-analysis>
<dynamic-analysis>
    <modules>
     <module sev0issue="0" sev1issue="14">
     </module>
    </modules>
</dynamic-analysis>
</summary-report>

How to parse and get the sev0issue under static analysis tag?

I'm trying below code to get the value.

value= ET.fromstring(XmlData) 
issue= value.find('.//summary-report/static-analysis/modules/module')
issueCount= issue.get('sev0issue') 

When I try this I'm getting error like there is no attrib sev0issue for Nonetype


Solution

  • import xml.etree.ElementTree as ET
    
    XmlData = '''<summary-report>
      <static-analysis>
        <modules>
         <module sev0issue="0" sev1issue="14">
         </module>
        </modules>
    </static-analysis>
    <dynamic-analysis>
        <modules>
         <module sev0issue="0" sev1issue="14">
         </module>
        </modules>
    </dynamic-analysis>
    </summary-report>'''
    
    summary_report = ET.fromstring(XmlData)
    
    # Method 1 prints both values from static and dynamic analysis
    for a in summary_report:
        for b in a:
            for c in b:
                print(c.attrib['sev0issue'])
    print()
    
    # Method 2
    print(summary_report[0][0][0].attrib['sev0issue'])
    

    outputs:

    0
    0
    
    0