0009-add-utils-to-access-XML-data-from-expression-31595.patch
passerelle/utils/xml.py | ||
---|---|---|
14 | 14 |
# You should have received a copy of the GNU Affero General Public License |
15 | 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
16 | 16 | |
17 |
from django.utils import six |
|
18 | ||
17 | 19 | |
18 | 20 |
def text_content(node): |
19 | 21 |
'''Extract text content from node and all its children. Equivalent to |
... | ... | |
81 | 83 |
if child_content: |
82 | 84 |
d[child.tag].append(child_content) |
83 | 85 |
return d |
86 | ||
87 | ||
88 |
@six.python_2_unicode_compatible |
|
89 |
class XMLAccessor(object): |
|
90 |
def __init__(self, root): |
|
91 |
self.root = root |
|
92 | ||
93 |
def __getattr__(self, name): |
|
94 |
def helper(): |
|
95 |
for child in self.root: |
|
96 |
localname = child.tag.rsplit('}', 1)[-1] |
|
97 |
if localname == name: |
|
98 |
yield child |
|
99 |
children = list(helper()) |
|
100 |
if len(children) == 0: |
|
101 |
return None |
|
102 |
elif len(children) > 1: |
|
103 |
raise Exception('too many children named %s' % name) |
|
104 |
else: |
|
105 |
return XMLAccessor(children[0]) |
|
106 | ||
107 |
def __str__(self): |
|
108 |
if len(self.root) == 0: |
|
109 |
return text_content(self.root) |
|
110 |
else: |
|
111 |
return '' |
|
112 | ||
113 | ||
114 |
def add_xml_accessor(d, root): |
|
115 |
localname = root.tag.rsplit('}', 1)[-1] |
|
116 |
d[localname] = XMLAccessor(root) |
tests/test_utils_xml.py | ||
---|---|---|
1 | 1 |
import xml.etree.ElementTree as ET |
2 | 2 | |
3 |
from passerelle.utils.xml import to_json, text_content |
|
3 |
from django.utils import six |
|
4 | ||
5 |
from passerelle.utils.xml import to_json, text_content, XMLAccessor, add_xml_accessor |
|
4 | 6 | |
5 | 7 | |
6 | 8 |
def test_text_content(): |
... | ... | |
31 | 33 |
{'text3': '4'}, |
32 | 34 |
] |
33 | 35 |
} |
36 | ||
37 | ||
38 |
def test_xml_accessor(): |
|
39 |
root = ET.fromstring('''<root xmlns:ns1="http://example.com"> |
|
40 |
<text1>1</text1> |
|
41 |
<text2>2</text2> |
|
42 |
<ns1:enfants> |
|
43 |
<enfant> |
|
44 |
<ns1:text3>4</ns1:text3> |
|
45 |
</enfant> |
|
46 |
<zob/> |
|
47 |
</ns1:enfants> |
|
48 |
<zob/> |
|
49 |
</root>''') |
|
50 |
d = {} |
|
51 |
add_xml_accessor(d, root) |
|
52 |
assert d['root'] |
|
53 |
assert six.text_type(d['root'].text1) == '1' |
|
54 |
assert six.text_type(d['root'].enfants.enfant.text3) == '4' |
|
34 |
- |