Data formats: XML, INI, TOML and pickle · 15 / 15 Exercise Hard

From XML to dictionary

Objective

Converting XML into Python structures (and then into JSON) is a common integration task between systems. It needs recursion and deciding what to do when a tag repeats.

Instructions

  • The input is a line with an XML document without attributes. An element without children becomes its text (empty string if it has none). One with children becomes a dictionary tag → value.
  • If a tag repeats among the children of the same element, its values form a list. Show {root: ...} on one line with json.dumps(..., sort_keys=True, ensure_ascii=False).
Input
<a><b>1</b><c>2</c></a>
Output
{"a": {"b": "1", "c": "2"}}

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise