Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 6b53b2f

Browse filesBrowse files
author
Kenneth Reitz
committed
Merge pull request realpython#311 from martinblech/master
Add xmltodict to xml scenario.
2 parents e66ca84 + bbbb24d commit 6b53b2f
Copy full SHA for 6b53b2f

File tree

Expand file treeCollapse file tree

1 file changed

+39
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+39
-0
lines changed

‎docs/scenarios/xml.rst

Copy file name to clipboardExpand all lines: docs/scenarios/xml.rst
+39Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,42 @@ and then you can get the child elements name like this:
3232
3333
untangle also supports loading XML from a string or an URL.
3434

35+
xmltodict
36+
---------
37+
38+
`xmltodict <http://github.com/martinblech/xmltodict>`_ is another simple
39+
library that aims at making xml feel like working with json.
40+
41+
An xml file like this:
42+
43+
.. code-block:: xml
44+
45+
<mydocument has="an attribute">
46+
<and>
47+
<many>elements</many>
48+
<many>more elements</many>
49+
</and>
50+
<plus a="complex">
51+
element as well
52+
</plus>
53+
</mydocument>
54+
55+
can be loaded into a python dict like this:
56+
57+
.. code-block:: python
58+
59+
import xmltodict
60+
obj = xmltodict.parse('path/to/file.xml')
61+
62+
and then you can access elements, attributes and values like this:
63+
64+
.. code-block:: python
65+
66+
doc['mydocument']['@has'] # == u'an attribute'
67+
doc['mydocument']['and']['many'] # == [u'elements', u'more elements']
68+
doc['mydocument']['plus']['@a'] # == u'complex'
69+
doc['mydocument']['plus']['#text'] # == u'element as well'
70+
71+
xmltodict also lets you roundtrip back to xml with the unparse function,
72+
has a streaming mode suitable for handling files that don't fit in memory
73+
and supports namespaces.

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.