Skip to content

Commit

Permalink
Support defaultdict for namespace mapping (#211)
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanalderson authored and martinblech committed Mar 28, 2019
1 parent a08bd4a commit 6a0bb9c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
30 changes: 30 additions & 0 deletions tests/test_xmltodict.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from xmltodict import parse, ParsingInterrupted
import collections
import unittest

try:
Expand Down Expand Up @@ -227,6 +228,35 @@ def test_namespace_collapse(self):
res = parse(xml, process_namespaces=True, namespaces=namespaces)
self.assertEqual(res, d)

def test_namespace_collapse_all(self):
xml = """
<root xmlns="http://defaultns.com/"
xmlns:a="http://a.com/"
xmlns:b="http://b.com/">
<x a:attr="val">1</x>
<a:y>2</a:y>
<b:z>3</b:z>
</root>
"""
namespaces = collections.defaultdict(lambda: None)
d = {
'root': {
'x': {
'@xmlns': {
'': 'http://defaultns.com/',
'a': 'http://a.com/',
'b': 'http://b.com/',
},
'@attr': 'val',
'#text': '1',
},
'y': '2',
'z': '3',
},
}
res = parse(xml, process_namespaces=True, namespaces=namespaces)
self.assertEqual(res, d)

def test_namespace_ignore(self):
xml = """
<root xmlns="http://defaultns.com/"
Expand Down
7 changes: 5 additions & 2 deletions xmltodict.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,16 @@ def __init__(self,
self.force_list = force_list

def _build_name(self, full_name):
if not self.namespaces:
if self.namespaces is None:
return full_name
i = full_name.rfind(self.namespace_separator)
if i == -1:
return full_name
namespace, name = full_name[:i], full_name[i+1:]
short_namespace = self.namespaces.get(namespace, namespace)
try:
short_namespace = self.namespaces[namespace]
except KeyError:
short_namespace = namespace
if not short_namespace:
return name
else:
Expand Down

0 comments on commit 6a0bb9c

Please sign in to comment.