Skip to content

Instantly share code, notes, and snippets.

@lukassup
Created July 11, 2016 00:18
Show Gist options
  • Save lukassup/17f27d2235f1e365e6e4b03d73238b24 to your computer and use it in GitHub Desktop.
Save lukassup/17f27d2235f1e365e6e4b03d73238b24 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
xml = '''\
<RECORDSET>
<RECORD ID="1">
<FIELDNAME>ORIGINALSEVERITY</FIELDNAME><FIELDVALUE>0</FIELDVALUE>
<FIELDNAME>TICKETID</FIELDNAME><FIELDVALUE></FIELDVALUE>
<FIELDNAME>EVENTSTATE</FIELDNAME><FIELDVALUE>1</FIELDVALUE>
</RECORD>
<RECORD ID="2">
<FIELDNAME>ORIGINALSEVERITY</FIELDNAME><FIELDVALUE>0</FIELDVALUE>
<FIELDNAME>TICKETID</FIELDNAME><FIELDVALUE></FIELDVALUE>
<FIELDNAME>EVENTSTATE</FIELDNAME><FIELDVALUE>0</FIELDVALUE>
</RECORD>
</RECORDSET>'''
def nc_parse(nc_xml):
alerts = list()
for rec in ET.fromstring(nc_xml).findall(".//RECORD"):
# Lowercase all keys for convenience
this = {k.lower(): v for k, v in rec.attrib.items()}
# Since odd elements are keys and even ones are values
# we can easily zip them. Keys lowercased
this.update(dict(zip(
[_.text.lower() for _ in rec.findall("./FIELDNAME")],
[_.text for _ in rec.findall("./FIELDVALUE")]
)))
alerts.append(this)
return alerts
print(nc_parse(xml))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment