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
CodePudding user response:
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.
CodePudding user response:
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