Conversion rules¶
| XML | Result |
|---|---|
<a/> |
{"a": None} |
<a>text</a> |
{"a": "text"} |
<a x="1"/> |
{"a": {"@x": "1"}} |
<a x="1">text</a> |
{"a": {"@x": "1", "#text": "text"}} |
<a><b>1</b></a> |
{"a": {"b": "1"}} |
<a><b>1</b><b>2</b></a> |
{"a": {"b": ["1", "2"]}} |
- All values are strings; nothing is converted to numbers or booleans.
- Surrounding whitespace is removed. Comments and processing instructions are ignored.
- Namespace prefixes are kept as written.
- The order between text and child elements is not kept.
Single value or list¶
One element of a name under a parent gives a single value; two or more give a list. The shape therefore depends on the number of elements.
print(expatjson.parse("<list><item>A</item></list>"))
# {'list': {'item': 'A'}} one -> string
print(expatjson.parse("<list><item>A</item><item>B</item></list>"))
# {'list': {'item': ['A', 'B']}} two or more -> list
print(expatjson.parse("<list/>"))
# {'list': None} none -> the element is absent
The same applies to elements with attributes.
print(expatjson.parse('<list><item id="1">A</item></list>'))
# {'list': {'item': {'@id': '1', '#text': 'A'}}}
print(expatjson.parse('<list><item id="1">A</item><item id="2">B</item></list>'))
# {'list': {'item': [{'@id': '1', '#text': 'A'}, {'@id': '2', '#text': 'B'}]}}
Elements of the same name are collected into one list even when other elements come between them.
print(expatjson.parse("<r><a>1</a><b>x</b><a>2</a></r>"))
# {'r': {'a': ['1', '2'], 'b': 'x'}}
Handle any number the same way¶
as_list gives a list for none, one or many. get_path never raises KeyError.
for xml in ("<list/>", "<list><item>A</item></list>", "<list><item>A</item><item>B</item></list>"):
doc = expatjson.parse(xml)
print(expatjson.as_list(expatjson.get_path(doc, "list", "item")))
# []
# ['A']
# ['A', 'B']