{"id":11257,"date":"2020-12-05T21:08:52","date_gmt":"2020-12-05T21:08:52","guid":{"rendered":"https:\/\/www.askpython.com\/?p=11257"},"modified":"2020-12-09T19:07:21","modified_gmt":"2020-12-09T19:07:21","slug":"xmltodict-module","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/xmltodict-module","title":{"rendered":"xmltodict Module in Python: A Practical Reference"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In this tutorial, we will see how to install the xmltodict module and use it in our Python programs to work easily with XML files. We will see how to convert XML to <a href=\"https:\/\/www.askpython.com\/python\/dictionary\/python-dictionary-dict-tutorial\" class=\"rank-math-link\">Python dictionaries<\/a> and to JSON format and vice-versa.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Install the xmltodict module using pip<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For Python 3 or above we can use the <a href=\"https:\/\/www.askpython.com\/python-modules\/python-pip\" class=\"rank-math-link\">pip3 command<\/a> to install xmltodict using the terminal.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npip3  install xmltodict\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">For older versions of Python we can use the following command to install xmltodict.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npip install xmltodict\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">What is an XML file?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">XML stands for extensible markup language and it was designed primarily for storing and transporting data. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s a descriptive language that supports writing structured data and we have to use other software to store, send, receive, or display XML data. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following XML file has data for an airplane such as the year, make, model and color.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: css; title: ; notranslate\" title=\"\">\n&lt;?xml version = &quot;1.0&quot; encoding = &quot;utf-8&quot;?&gt;\n&lt;!-- xslplane.1.xml --&gt;\n&lt;?xml-stylesheet type = &quot;text\/xsl&quot;  href = &quot;xslplane.1.xsl&quot; ?&gt;\n&lt;plane&gt;\n   &lt;year&gt; 1977 &lt;\/year&gt;\n   &lt;make&gt; Cessna &lt;\/make&gt;\n   &lt;model&gt; Skyhawk &lt;\/model&gt;\n   &lt;color&gt; Light blue and white &lt;\/color&gt;\n&lt;\/plane&gt;\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Now, in the following sections, we will play with this airplane data and see how to convert it into Python dictionary and JSON and convert them back to XML format using the xmltodict module.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to read XML data into a Python dictionary?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We can convert XML files to a Python dictionary using the <code>xmltodict.parse()<\/code> method in the xmltodict module. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>xmltodict.parse() <\/code>method takes an XML file as input and changes it to Ordered Dictionary. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can then extract the dictionary data from Ordered Dictionary using dict constructor for Python dictionaries. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#import module\nimport xmltodict\n\n#open the file\nfileptr = open(&quot;\/home\/aditya1117\/askpython\/plane.xml&quot;,&quot;r&quot;)\n\n#read xml content from the file\nxml_content= fileptr.read()\nprint(&quot;XML content is:&quot;)\nprint(xml_content)\n\n#change xml format to ordered dict\nmy_ordered_dict=xmltodict.parse(xml_content)\nprint(&quot;Ordered Dictionary is:&quot;)\nprint(my_ordered_dict)\nprint(&quot;Year of plane is:&quot;)\nprint(my_ordered_dict&#x5B;&#039;plane&#039;]&#x5B;&#039;year&#039;])\n\n#Use contents of ordered dict to make python dictionary\nmy_plane= dict(my_ordered_dict&#x5B;&#039;plane&#039;])\nprint(&quot;Created dictionary data is:&quot;)\nprint(my_plane)\nprint(&quot;Year of plane is&quot;)\nprint(my_plane&#x5B;&#039;year&#039;])\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nXML content is:\n&lt;?xml version = &quot;1.0&quot; encoding = &quot;utf-8&quot;?&gt;\n&lt;!-- xslplane.1.xml --&gt;\n&lt;?xml-stylesheet type = &quot;text\/xsl&quot;  href = &quot;xslplane.1.xsl&quot; ?&gt;\n&lt;plane&gt;\n   &lt;year&gt; 1977 &lt;\/year&gt;\n   &lt;make&gt; Cessna &lt;\/make&gt;\n   &lt;model&gt; Skyhawk &lt;\/model&gt;\n   &lt;color&gt; Light blue and white &lt;\/color&gt;\n&lt;\/plane&gt;\n\nOrdered Dictionary is:\nOrderedDict(&#x5B;(&#039;plane&#039;, OrderedDict(&#x5B;(&#039;year&#039;, &#039;1977&#039;), (&#039;make&#039;, &#039;Cessna&#039;), (&#039;model&#039;, &#039;Skyhawk&#039;), (&#039;color&#039;, &#039;Light blue and white&#039;)]))])\nYear of plane is:\n1977\nCreated dictionary data is:\n{&#039;year&#039;: &#039;1977&#039;, &#039;make&#039;: &#039;Cessna&#039;, &#039;model&#039;: &#039;Skyhawk&#039;, &#039;color&#039;: &#039;Light blue and white&#039;}\nYear of plane is\n1977\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">In the above example, we have successfully extracted our airplane data from XML format using <strong><code>xmltodict.parse()<\/code><\/strong> method and printed the data both in the form of Ordered Dictionary and dictionary.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to convert a Python dictionary to XML?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We can convert a python dictionary into the XML format using <strong><code>xmltodict.unparse()<\/code><\/strong> method of xmltodict module. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This method accepts the dictionary object as input as returns an XML format data as output. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The only restriction here is that <strong>the dictionary should have single root <\/strong>so that XML data can be formatted easily. Otherwise it will cause <strong><code>ValueError<\/code><\/strong> .<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#import module\nimport xmltodict\n\n#define dictionary with all the attributes\nmydict={&#039;plane&#039;:{&#039;year&#039;: &#039;1977&#039;, &#039;make&#039;: &#039;Cessna&#039;, &#039;model&#039;: &#039;Skyhawk&#039;, &#039;color&#039;:&#039;Light blue and white&#039;}}\nprint(&quot;Original Dictionary of plane data is:&quot;)\nprint(mydict)\n\n#create xml format\nxml_format= xmltodict.unparse(my_ordered_dict,pretty=True)\nprint(&quot;XML format data is:&quot;)\nprint(xml_format)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nOriginal Dictionary of plane data is:\n{&#039;plane&#039;: {&#039;year&#039;: &#039;1977&#039;, &#039;make&#039;: &#039;Cessna&#039;, &#039;model&#039;: &#039;Skyhawk&#039;, &#039;color&#039;: &#039;Light blue and white&#039;}}\nXML format data is:\n&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;\n&lt;plane&gt;\n        &lt;year&gt;1977&lt;\/year&gt;\n        &lt;make&gt;Cessna&lt;\/make&gt;\n        &lt;model&gt;Skyhawk&lt;\/model&gt;\n        &lt;color&gt;Light blue and white&lt;\/color&gt;\n&lt;\/plane&gt;\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">In the above example, we have created airplane data in XML format  from simple python dictionary data. Now we will see how to convert XML data into JSON format.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to convert XML to JSON?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We can convert XML data into JSON format using the <strong>xmltodict<\/strong> module and the <a href=\"https:\/\/www.askpython.com\/python-modules\/python-json-module\" class=\"rank-math-link\"><strong>json<\/strong> module in python<\/a>. In this process, we first create an ordered dictionary from XML format using <strong><code>xmltodict.parse()<\/code><\/strong> method. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then we convert the ordered dictionary into JSON format using <strong><code>json.dumps()<\/code><\/strong> method which takes ordered dictionary as an argument and converts it into JSON string.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#import module\nimport xmltodict\nimport json\n\n#open the file\nfileptr = open(&quot;\/home\/aditya1117\/askpython\/plane.xml&quot;,&quot;r&quot;)\n\n#read xml content from the file\nxml_content= fileptr.read()\nprint(&quot;XML content is:&quot;)\nprint(xml_content)\n\n#change xml format to ordered dict\nmy_ordered_dict=xmltodict.parse(xml_content)\nprint(&quot;Ordered Dictionary is:&quot;)\nprint(my_ordered_dict)\njson_data= json.dumps(my_ordered_dict)\nprint(&quot;JSON data is:&quot;)\nprint(json_data)\nx= open(&quot;plane.json&quot;,&quot;w&quot;)\nx.write(json_data)\nx.close()\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nXML content is:\n&lt;?xml version = &quot;1.0&quot; encoding = &quot;utf-8&quot;?&gt;\n&lt;!-- xslplane.1.xml --&gt;\n&lt;?xml-stylesheet type = &quot;text\/xsl&quot;  href = &quot;xslplane.1.xsl&quot; ?&gt;\n&lt;plane&gt;\n   &lt;year&gt; 1977 &lt;\/year&gt;\n   &lt;make&gt; Cessna &lt;\/make&gt;\n   &lt;model&gt; Skyhawk &lt;\/model&gt;\n   &lt;color&gt; Light blue and white &lt;\/color&gt;\n&lt;\/plane&gt;\n\nOrdered Dictionary is:\nOrderedDict(&#x5B;(&#039;plane&#039;, OrderedDict(&#x5B;(&#039;year&#039;, &#039;1977&#039;), (&#039;make&#039;, &#039;Cessna&#039;), (&#039;model&#039;, &#039;Skyhawk&#039;), (&#039;color&#039;, &#039;Light blue and white&#039;)]))])\nJSON data is:\n{&quot;plane&quot;: {&quot;year&quot;: &quot;1977&quot;, &quot;make&quot;: &quot;Cessna&quot;, &quot;model&quot;: &quot;Skyhawk&quot;, &quot;color&quot;: &quot;Light blue and white&quot;}}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">In the above example, we have read XML data into <strong><code>xml_content<\/code><\/strong> and then <strong><code>xmltodict.parse() <\/code><\/strong>creates an ordered dictionary <strong><code>my_ordered_dict<\/code><\/strong> and then JSON data is created using <strong><code>json.dumps()<\/code><\/strong> method from ordered dictionary.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to convert JSON data to XML?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s convert JSON data into the XML format using the xmltodict module by first converting the JSON data to Python dictionary using <strong><code>json.load()<\/code><\/strong> method and then converting the dictionary to XML using <strong><code>xmltodict.unparse()<\/code><\/strong>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Again, here restriction is that <strong>JSON data should have a single root<\/strong> otherwise it will cause <strong><code>ValueError<\/code><\/strong>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#import module\nimport xmltodict\nimport json\n\n#define dictionary with all the attributes\nfileptr = open(&quot;\/home\/aditya1117\/askpython\/plane.json&quot;,&quot;r&quot;)\njson_data=json.load(fileptr)\nprint(&quot;JSON data is:&quot;)\nprint(json_data)\n\n#create xml format\nxml_format= xmltodict.unparse(json_data,pretty=True)\nprint(&quot;XML format data is:&quot;)\nprint(xml_format)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nJSON data is:\n{&#039;plane&#039;: {&#039;year&#039;: &#039;1977&#039;, &#039;make&#039;: &#039;Cessna&#039;, &#039;model&#039;: &#039;Skyhawk&#039;, &#039;color&#039;: &#039;Light blue and white&#039;}}\nXML format data is:\n&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;\n&lt;plane&gt;\n        &lt;year&gt;1977&lt;\/year&gt;\n        &lt;make&gt;Cessna&lt;\/make&gt;\n        &lt;model&gt;Skyhawk&lt;\/model&gt;\n        &lt;color&gt;Light blue and white&lt;\/color&gt;\n&lt;\/plane&gt;\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">In the above example,<strong><code> json.load()<\/code><\/strong> accepts the file object as argument and parses the data thereby creating a Python dictionary which is stored in <strong><code>json_data<\/code><\/strong> . Then we convert the dictionary into XML file using <strong><code>xmltodict.unparse()<\/code><\/strong> method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this article, we have used the xmltodict module to process XML data. We have seen how to convert XML data to Python dictionary and JSON format and also converted them back into XML format. Happy Learning!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will see how to install the xmltodict module and use it in our Python programs to work easily with XML files. We will see how to convert XML to Python dictionaries and to JSON format and vice-versa. Install the xmltodict module using pip For Python 3 or above we can use [&hellip;]<\/p>\n","protected":false},"author":20,"featured_media":11327,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,9],"tags":[],"class_list":["post-11257","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/11257","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/20"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=11257"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/11257\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/11327"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=11257"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=11257"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=11257"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}