xmltodict.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #!/usr/bin/env python
  2. "Makes working with XML feel like you are working with JSON"
  3. try:
  4. from defusedexpat import pyexpat as expat
  5. except ImportError:
  6. from xml.parsers import expat
  7. from xml.sax.saxutils import XMLGenerator
  8. from xml.sax.xmlreader import AttributesImpl
  9. try: # pragma no cover
  10. from cStringIO import StringIO
  11. except ImportError: # pragma no cover
  12. try:
  13. from StringIO import StringIO
  14. except ImportError:
  15. from io import StringIO
  16. try: # pragma no cover
  17. from collections import OrderedDict
  18. except ImportError: # pragma no cover
  19. try:
  20. from ordereddict import OrderedDict
  21. except ImportError:
  22. OrderedDict = dict
  23. try: # pragma no cover
  24. _basestring = basestring
  25. except NameError: # pragma no cover
  26. _basestring = str
  27. try: # pragma no cover
  28. _unicode = unicode
  29. except NameError: # pragma no cover
  30. _unicode = str
  31. __author__ = 'Martin Blech'
  32. __version__ = '0.11.0'
  33. __license__ = 'MIT'
  34. class ParsingInterrupted(Exception):
  35. pass
  36. class _DictSAXHandler(object):
  37. def __init__(self,
  38. item_depth=0,
  39. item_callback=lambda *args: True,
  40. xml_attribs=True,
  41. attr_prefix='@',
  42. cdata_key='#text',
  43. force_cdata=False,
  44. cdata_separator='',
  45. postprocessor=None,
  46. dict_constructor=OrderedDict,
  47. strip_whitespace=True,
  48. namespace_separator=':',
  49. namespaces=None,
  50. force_list=None):
  51. self.path = []
  52. self.stack = []
  53. self.data = []
  54. self.item = None
  55. self.item_depth = item_depth
  56. self.xml_attribs = xml_attribs
  57. self.item_callback = item_callback
  58. self.attr_prefix = attr_prefix
  59. self.cdata_key = cdata_key
  60. self.force_cdata = force_cdata
  61. self.cdata_separator = cdata_separator
  62. self.postprocessor = postprocessor
  63. self.dict_constructor = dict_constructor
  64. self.strip_whitespace = strip_whitespace
  65. self.namespace_separator = namespace_separator
  66. self.namespaces = namespaces
  67. self.namespace_declarations = OrderedDict()
  68. self.force_list = force_list
  69. def _build_name(self, full_name):
  70. if not self.namespaces:
  71. return full_name
  72. i = full_name.rfind(self.namespace_separator)
  73. if i == -1:
  74. return full_name
  75. namespace, name = full_name[:i], full_name[i+1:]
  76. short_namespace = self.namespaces.get(namespace, namespace)
  77. if not short_namespace:
  78. return name
  79. else:
  80. return self.namespace_separator.join((short_namespace, name))
  81. def _attrs_to_dict(self, attrs):
  82. if isinstance(attrs, dict):
  83. return attrs
  84. return self.dict_constructor(zip(attrs[0::2], attrs[1::2]))
  85. def startNamespaceDecl(self, prefix, uri):
  86. self.namespace_declarations[prefix or ''] = uri
  87. def startElement(self, full_name, attrs):
  88. name = self._build_name(full_name)
  89. attrs = self._attrs_to_dict(attrs)
  90. if attrs and self.namespace_declarations:
  91. attrs['xmlns'] = self.namespace_declarations
  92. self.namespace_declarations = OrderedDict()
  93. self.path.append((name, attrs or None))
  94. if len(self.path) > self.item_depth:
  95. self.stack.append((self.item, self.data))
  96. if self.xml_attribs:
  97. attr_entries = []
  98. for key, value in attrs.items():
  99. key = self.attr_prefix+self._build_name(key)
  100. if self.postprocessor:
  101. entry = self.postprocessor(self.path, key, value)
  102. else:
  103. entry = (key, value)
  104. if entry:
  105. attr_entries.append(entry)
  106. attrs = self.dict_constructor(attr_entries)
  107. else:
  108. attrs = None
  109. self.item = attrs or None
  110. self.data = []
  111. def endElement(self, full_name):
  112. name = self._build_name(full_name)
  113. if len(self.path) == self.item_depth:
  114. item = self.item
  115. if item is None:
  116. item = (None if not self.data
  117. else self.cdata_separator.join(self.data))
  118. should_continue = self.item_callback(self.path, item)
  119. if not should_continue:
  120. raise ParsingInterrupted()
  121. if len(self.stack):
  122. data = (None if not self.data
  123. else self.cdata_separator.join(self.data))
  124. item = self.item
  125. self.item, self.data = self.stack.pop()
  126. if self.strip_whitespace and data:
  127. data = data.strip() or None
  128. if data and self.force_cdata and item is None:
  129. item = self.dict_constructor()
  130. if item is not None:
  131. if data:
  132. self.push_data(item, self.cdata_key, data)
  133. self.item = self.push_data(self.item, name, item)
  134. else:
  135. self.item = self.push_data(self.item, name, data)
  136. else:
  137. self.item = None
  138. self.data = []
  139. self.path.pop()
  140. def characters(self, data):
  141. if not self.data:
  142. self.data = [data]
  143. else:
  144. self.data.append(data)
  145. def push_data(self, item, key, data):
  146. if self.postprocessor is not None:
  147. result = self.postprocessor(self.path, key, data)
  148. if result is None:
  149. return item
  150. key, data = result
  151. if item is None:
  152. item = self.dict_constructor()
  153. try:
  154. value = item[key]
  155. if isinstance(value, list):
  156. value.append(data)
  157. else:
  158. item[key] = [value, data]
  159. except KeyError:
  160. if self._should_force_list(key, data):
  161. item[key] = [data]
  162. else:
  163. item[key] = data
  164. return item
  165. def _should_force_list(self, key, value):
  166. if not self.force_list:
  167. return False
  168. try:
  169. return key in self.force_list
  170. except TypeError:
  171. return self.force_list(self.path[:-1], key, value)
  172. def parse(xml_input, encoding=None, expat=expat, process_namespaces=False,
  173. namespace_separator=':', disable_entities=True, **kwargs):
  174. """Parse the given XML input and convert it into a dictionary.
  175. `xml_input` can either be a `string` or a file-like object.
  176. If `xml_attribs` is `True`, element attributes are put in the dictionary
  177. among regular child elements, using `@` as a prefix to avoid collisions. If
  178. set to `False`, they are just ignored.
  179. Simple example::
  180. >>> import xmltodict
  181. >>> doc = xmltodict.parse(\"\"\"
  182. ... <a prop="x">
  183. ... <b>1</b>
  184. ... <b>2</b>
  185. ... </a>
  186. ... \"\"\")
  187. >>> doc['a']['@prop']
  188. u'x'
  189. >>> doc['a']['b']
  190. [u'1', u'2']
  191. If `item_depth` is `0`, the function returns a dictionary for the root
  192. element (default behavior). Otherwise, it calls `item_callback` every time
  193. an item at the specified depth is found and returns `None` in the end
  194. (streaming mode).
  195. The callback function receives two parameters: the `path` from the document
  196. root to the item (name-attribs pairs), and the `item` (dict). If the
  197. callback's return value is false-ish, parsing will be stopped with the
  198. :class:`ParsingInterrupted` exception.
  199. Streaming example::
  200. >>> def handle(path, item):
  201. ... print('path:%s item:%s' % (path, item))
  202. ... return True
  203. ...
  204. >>> xmltodict.parse(\"\"\"
  205. ... <a prop="x">
  206. ... <b>1</b>
  207. ... <b>2</b>
  208. ... </a>\"\"\", item_depth=2, item_callback=handle)
  209. path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1
  210. path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2
  211. The optional argument `postprocessor` is a function that takes `path`,
  212. `key` and `value` as positional arguments and returns a new `(key, value)`
  213. pair where both `key` and `value` may have changed. Usage example::
  214. >>> def postprocessor(path, key, value):
  215. ... try:
  216. ... return key + ':int', int(value)
  217. ... except (ValueError, TypeError):
  218. ... return key, value
  219. >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>',
  220. ... postprocessor=postprocessor)
  221. OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))])
  222. You can pass an alternate version of `expat` (such as `defusedexpat`) by
  223. using the `expat` parameter. E.g:
  224. >>> import defusedexpat
  225. >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat)
  226. OrderedDict([(u'a', u'hello')])
  227. You can use the force_list argument to force lists to be created even
  228. when there is only a single child of a given level of hierarchy. The
  229. force_list argument is a tuple of keys. If the key for a given level
  230. of hierarchy is in the force_list argument, that level of hierarchy
  231. will have a list as a child (even if there is only one sub-element).
  232. The index_keys operation takes precendence over this. This is applied
  233. after any user-supplied postprocessor has already run.
  234. For example, given this input:
  235. <servers>
  236. <server>
  237. <name>host1</name>
  238. <os>Linux</os>
  239. <interfaces>
  240. <interface>
  241. <name>em0</name>
  242. <ip_address>10.0.0.1</ip_address>
  243. </interface>
  244. </interfaces>
  245. </server>
  246. </servers>
  247. If called with force_list=('interface',), it will produce
  248. this dictionary:
  249. {'servers':
  250. {'server':
  251. {'name': 'host1',
  252. 'os': 'Linux'},
  253. 'interfaces':
  254. {'interface':
  255. [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } }
  256. `force_list` can also be a callable that receives `path`, `key` and
  257. `value`. This is helpful in cases where the logic that decides whether
  258. a list should be forced is more complex.
  259. """
  260. handler = _DictSAXHandler(namespace_separator=namespace_separator,
  261. **kwargs)
  262. if isinstance(xml_input, _unicode):
  263. if not encoding:
  264. encoding = 'utf-8'
  265. xml_input = xml_input.encode(encoding)
  266. if not process_namespaces:
  267. namespace_separator = None
  268. parser = expat.ParserCreate(
  269. encoding,
  270. namespace_separator
  271. )
  272. try:
  273. parser.ordered_attributes = True
  274. except AttributeError:
  275. # Jython's expat does not support ordered_attributes
  276. pass
  277. parser.StartNamespaceDeclHandler = handler.startNamespaceDecl
  278. parser.StartElementHandler = handler.startElement
  279. parser.EndElementHandler = handler.endElement
  280. parser.CharacterDataHandler = handler.characters
  281. parser.buffer_text = True
  282. if disable_entities:
  283. try:
  284. # Attempt to disable DTD in Jython's expat parser (Xerces-J).
  285. feature = "http://apache.org/xml/features/disallow-doctype-decl"
  286. parser._reader.setFeature(feature, True)
  287. except AttributeError:
  288. # For CPython / expat parser.
  289. # Anything not handled ends up here and entities aren't expanded.
  290. parser.DefaultHandler = lambda x: None
  291. # Expects an integer return; zero means failure -> expat.ExpatError.
  292. parser.ExternalEntityRefHandler = lambda *x: 1
  293. if hasattr(xml_input, 'read'):
  294. parser.ParseFile(xml_input)
  295. else:
  296. parser.Parse(xml_input, True)
  297. return handler.item
  298. def _process_namespace(name, namespaces, ns_sep=':', attr_prefix='@'):
  299. if not namespaces:
  300. return name
  301. try:
  302. ns, name = name.rsplit(ns_sep, 1)
  303. except ValueError:
  304. pass
  305. else:
  306. ns_res = namespaces.get(ns.strip(attr_prefix))
  307. name = '{0}{1}{2}{3}'.format(
  308. attr_prefix if ns.startswith(attr_prefix) else '',
  309. ns_res, ns_sep, name) if ns_res else name
  310. return name
  311. def _emit(key, value, content_handler,
  312. attr_prefix='@',
  313. cdata_key='#text',
  314. depth=0,
  315. preprocessor=None,
  316. pretty=False,
  317. newl='\n',
  318. indent='\t',
  319. namespace_separator=':',
  320. namespaces=None,
  321. full_document=True):
  322. key = _process_namespace(key, namespaces, namespace_separator, attr_prefix)
  323. if preprocessor is not None:
  324. result = preprocessor(key, value)
  325. if result is None:
  326. return
  327. key, value = result
  328. if (not hasattr(value, '__iter__')
  329. or isinstance(value, _basestring)
  330. or isinstance(value, dict)):
  331. value = [value]
  332. for index, v in enumerate(value):
  333. if full_document and depth == 0 and index > 0:
  334. raise ValueError('document with multiple roots')
  335. if v is None:
  336. v = OrderedDict()
  337. elif not isinstance(v, dict):
  338. v = _unicode(v)
  339. if isinstance(v, _basestring):
  340. v = OrderedDict(((cdata_key, v),))
  341. cdata = None
  342. attrs = OrderedDict()
  343. children = []
  344. for ik, iv in v.items():
  345. if ik == cdata_key:
  346. cdata = iv
  347. continue
  348. if ik.startswith(attr_prefix):
  349. ik = _process_namespace(ik, namespaces, namespace_separator,
  350. attr_prefix)
  351. if ik == '@xmlns' and isinstance(iv, dict):
  352. for k, v in iv.items():
  353. attr = 'xmlns{0}'.format(':{0}'.format(k) if k else '')
  354. attrs[attr] = _unicode(v)
  355. continue
  356. if not isinstance(iv, _unicode):
  357. iv = _unicode(iv)
  358. attrs[ik[len(attr_prefix):]] = iv
  359. continue
  360. children.append((ik, iv))
  361. if pretty:
  362. content_handler.ignorableWhitespace(depth * indent)
  363. content_handler.startElement(key, AttributesImpl(attrs))
  364. if pretty and children:
  365. content_handler.ignorableWhitespace(newl)
  366. for child_key, child_value in children:
  367. _emit(child_key, child_value, content_handler,
  368. attr_prefix, cdata_key, depth+1, preprocessor,
  369. pretty, newl, indent, namespaces=namespaces,
  370. namespace_separator=namespace_separator)
  371. if cdata is not None:
  372. content_handler.characters(cdata)
  373. if pretty and children:
  374. content_handler.ignorableWhitespace(depth * indent)
  375. content_handler.endElement(key)
  376. if pretty and depth:
  377. content_handler.ignorableWhitespace(newl)
  378. def unparse(input_dict, output=None, encoding='utf-8', full_document=True,
  379. short_empty_elements=False,
  380. **kwargs):
  381. """Emit an XML document for the given `input_dict` (reverse of `parse`).
  382. The resulting XML document is returned as a string, but if `output` (a
  383. file-like object) is specified, it is written there instead.
  384. Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
  385. as XML node attributes, whereas keys equal to `cdata_key`
  386. (default=`'#text'`) are treated as character data.
  387. The `pretty` parameter (default=`False`) enables pretty-printing. In this
  388. mode, lines are terminated with `'\n'` and indented with `'\t'`, but this
  389. can be customized with the `newl` and `indent` parameters.
  390. """
  391. if full_document and len(input_dict) != 1:
  392. raise ValueError('Document must have exactly one root.')
  393. must_return = False
  394. if output is None:
  395. output = StringIO()
  396. must_return = True
  397. if short_empty_elements:
  398. content_handler = XMLGenerator(output, encoding, True)
  399. else:
  400. content_handler = XMLGenerator(output, encoding)
  401. if full_document:
  402. content_handler.startDocument()
  403. for key, value in input_dict.items():
  404. _emit(key, value, content_handler, full_document=full_document,
  405. **kwargs)
  406. if full_document:
  407. content_handler.endDocument()
  408. if must_return:
  409. value = output.getvalue()
  410. try: # pragma no cover
  411. value = value.decode(encoding)
  412. except AttributeError: # pragma no cover
  413. pass
  414. return value
  415. if __name__ == '__main__': # pragma: no cover
  416. import sys
  417. import marshal
  418. try:
  419. stdin = sys.stdin.buffer
  420. stdout = sys.stdout.buffer
  421. except AttributeError:
  422. stdin = sys.stdin
  423. stdout = sys.stdout
  424. (item_depth,) = sys.argv[1:]
  425. item_depth = int(item_depth)
  426. def handle_item(path, item):
  427. marshal.dump((path, item), stdout)
  428. return True
  429. try:
  430. root = parse(stdin,
  431. item_depth=item_depth,
  432. item_callback=handle_item,
  433. dict_constructor=dict)
  434. if item_depth == 0:
  435. handle_item([], root)
  436. except KeyboardInterrupt:
  437. pass