Skip to content
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

added namespace handling (xml -> dict) #9

Open
wants to merge 2 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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ Example
... ''')
{'root': {'persons': {'person': [{'name': {'last': 'bar', 'first': 'foo'}}, {'name': {'last': 'bar', 'first': 'baz'}}]}}}

# Removing namespace during convertion to dictionary is optional
>>> xmldict.xml_to_dict("""<root id="1" xmlns="somenamespace"><items><item>1</item><item>2</item></items></root>""", remove_namespace=True)
{'root': {'items': {'item': ['1', '2']}}}

# Converting dictionary to xml
>>> xmldict.dict_to_xml({'root': {'persons': {'person': [{'name': {'last': 'bar', 'first': 'foo'}}, {'name': {'last': 'bar', 'first': 'baz'}}]}}})
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@

from setuptools import setup
setup(name='xmldict',
version='0.4.1',
version='0.5.0',
description='Convert xml to python dictionaries.',
long_description=__doc__,
author='Rahul Kumar',
Expand Down
14 changes: 14 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,20 @@ def test_xml_to_dict_order(self):
self.assertEqual(expected, xml_to_dict(order1))
self.assertEqual(expected, xml_to_dict(order2))

def test_xml_to_dict_namespace(self):
xml_str1 = """<root id="1" xmlns="somenamespace"><items><item>1</item><item>2</item></items></root>"""
xml_str2 = """<root id="1"><items><item>1</item><item>2</item></items></root>"""
expected1 = {'{somenamespace}root': {'{somenamespace}items': {'{somenamespace}item': ['1', '2']}}}
expected2 = {'root': {'items': {'item': ['1', '2']}}}
self.assertEqual(expected1, xml_to_dict(xml_str1, strict=False))
self.assertEqual(expected1, xml_to_dict(xml_str1))
self.assertEqual(expected2, xml_to_dict(xml_str1, False, True))
self.assertEqual(expected2, xml_to_dict(xml_str1, remove_namespace=True))
self.assertEqual(expected2, xml_to_dict(xml_str2, strict=False))
self.assertEqual(expected2, xml_to_dict(xml_str2))
self.assertEqual(expected2, xml_to_dict(xml_str2, False, True))
self.assertEqual(expected2, xml_to_dict(xml_str2, remove_namespace=True))

def test_dict_to_xml_simple(self):
dict_xml = {'transaction': {'amount': '100.00', 'currency_code': 'USD'}}
expected = '<transaction><amount>100.00</amount><currency_code>USD</currency_code></transaction>'
Expand Down
18 changes: 14 additions & 4 deletions xmldict.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"""
import datetime

def xml_to_dict(root_or_str, strict=True):
def xml_to_dict(root_or_str, strict=True, remove_namespace=False):
"""
Converts `root_or_str` which can be parsed xml or a xml string to dict.

Expand All @@ -15,7 +15,10 @@ def xml_to_dict(root_or_str, strict=True):
if isinstance(root, str):
import xml.etree.cElementTree as ElementTree
root = ElementTree.XML(root_or_str)
return {root.tag: _from_xml(root, strict)}
the_tag = root.tag
if remove_namespace:
the_tag = _remove_namespace(root.tag)
return {the_tag: _from_xml(root, strict, remove_namespace)}

def dict_to_xml(dict_xml):
"""
Expand Down Expand Up @@ -86,7 +89,7 @@ def _str_to_boolean(bool_str):
return True
return False

def _from_xml(el, strict):
def _from_xml(el, strict, rem_ns):
"""
Extracts value of xml element element `el`.
"""
Expand All @@ -96,7 +99,9 @@ def _from_xml(el, strict):
val = {}
for e in el:
tag = e.tag
v = _from_xml(e, strict)
if rem_ns:
tag = _remove_namespace(tag)
v = _from_xml(e, strict, rem_ns)
if tag in val:
# Multiple elements share this tag, make them a list
if not isinstance(val[tag], list):
Expand Down Expand Up @@ -140,3 +145,8 @@ def _val_and_maybe_convert(el):
'integer': int
}

def _remove_namespace(tag):
if tag.find("{") >= 0 and tag.find("}") >= 0:
return tag[:tag.find("{")] + tag[(tag.find("}")+1):]
else:
return tag