Skip to content

Instantly share code, notes, and snippets.

@ErDmKo
Last active February 25, 2023 07:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ErDmKo/010849e53fac8e0071a5 to your computer and use it in GitHub Desktop.
Save ErDmKo/010849e53fac8e0071a5 to your computer and use it in GitHub Desktop.
simple convert xml to json with lxml
from lxml import etree
root = etree.fromstring(xml_str)
def xml2json(self, root):
children = root.findall('ResponseData/ResponseDataObject')[0]
def recusiv(children):
out = {}
for child in list(children):
if len(list(child)):
if child.tag not in out:
out[child.tag] = []
out[child.tag].append(recusiv(child))
else:
out[child.tag] = child.text
return out
return recusiv(children)
'''
in fo
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<ResponseData>
<ResponseDataObject>
<leve1>
<leve2>asd</leve2>
<leve2a>1</leve2a>
<leve2b>
<leve3>12</leve3>
<leve3a>12</leve3a>
<leve3b>12</leve3b>
</leve2b>
<level2c>500</level2c>
</level1>
<level1>
<leve2>asd</leve2>
<leve2a>1</leve2a>
<leve2b>
<leve3>12</leve3>
<leve3a>12</leve3a>
<leve3b>12</leve3b>
</leve2b>
<level2c>500</level2c>
</level1>
</ResponseDataObject>
</ResponseData>
</Response>
from function
{
'level1': [{
'leve2': 'asd',
'leve2a': '1',
'leve2b': [{
'leve3': '12',
'leve3a': '12',
'leve3b': '12',
}]
'leve2c': '500',
},{
'leve2': 'asd',
'leve2a': '1',
'leve2b': [{
'leve3': '12',
'leve3a': '12',
'leve3b': '12',
}]
'leve2c': '500',
}]
}
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment