0

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

1
  • Where is the code? What is the error? Commented Jul 21, 2022 at 17:49

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

Not really sure why, but with ElementTree you don't start searching from the root element. The correct version would be:

issue = value.find('.//static-analysis/modules/module')
issue.get('sev0issue') 

If you use lxml, on the other hand, it's more intuitive:

from lxml import etree
value= etree.fromstring(XmlData) 
values.xpath('/summary-report/static-analysis/modules/module/@sev0issue')

Same output.

1 Comment

Tried the Element tree but still got NoneType has no attribute of sev0issue. Tried lxml way and got empty values as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.