Skip to content

Handle/parse XML attributes: https://github.com/jpadilla/django-rest-framework-xml/issues/16 #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions rest_framework_xml/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,21 @@ def _xml_convert(self, element):
if len(children) == 0:
return self._type_convert(element.text)
else:
# if the fist child tag is list-item means all children are list-item
# if first child tag is list-item means all children are list-item
if children[0].tag == "list-item":
data = []
for child in children:
data.append(self._xml_convert(child))
else:
data = {}
for child in children:
data[child.tag] = self._xml_convert(child)
if child.attrib:
data[child.tag] = {
'value': self._xml_convert(child),
'attributes': child.attrib
}
else:
data[child.tag] = self._xml_convert(child)

return data

Expand Down
32 changes: 32 additions & 0 deletions tests/test_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,32 @@ def setUp(self):
}
]
}
self._attribute_data_input = StringIO(
'<?xml version="1.0" encoding="utf-8"?>'
'<root>'
'<field_a name="attribute_a">121.0</field_a>'
'<field_b id="0001" name="attribute_b">dasd</field_b>'
'<field_c></field_c>'
'<field_d>2011-12-25 12:45:00</field_d>'
'</root>'
)
self._attribute_data = {
'field_a': {
'value': 121,
'attributes': {
'name': 'attribute_a'
}
},
'field_b': {
'value': 'dasd',
'attributes': {
'id': '0001',
'name': 'attribute_b'
}
},
'field_c': None,
'field_d': datetime.datetime(2011, 12, 25, 12, 45, 00)
}

@skipUnless(etree, 'defusedxml not installed')
def test_parse(self):
Expand All @@ -64,3 +90,9 @@ def test_complex_data_parse(self):
parser = XMLParser()
data = parser.parse(self._complex_data_input)
self.assertEqual(data, self._complex_data)

@skipUnless(etree, 'defusedxml not installed')
def test_complex_data_parse(self):
parser = XMLParser()
data = parser.parse(self._attribute_data_input)
self.assertEqual(data, self._attribute_data)