<p>XML is a popular way of storing data in a hierarchical arrangement so that the data can be parsed later. For instance, here is a simple XML snippet:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;book&gt;
   &lt;chapter id=&quot;prologue&quot;&gt;
      &lt;title&gt;
     The Beginning
 &lt;/title&gt;
   &lt;/chapter&gt;
&lt;/book&gt;</code></pre>
<p>The nice thing about XML is that it is explicit and strictly structured. The trade-off is that it's pretty verbose, and getting to where you want to go often requires fairly complex navigation.</p>
<p>If you do a quick search online for XML parsing in Python, your two most common results are <code>lxml</code> and <code>beautifulsoup</code>. These both work, but using them feels less like opening a dictionary (as with JSON) to look up a definition and more like wandering through a library to gather up all the dictionaries you can possibly find.</p>
<p>In JSON, the thought process might be something like:</p>
<p>&quot;Go to the first chapter's title and print the contents.&quot;</p>
<p>With traditional XML tools, it's more like:</p>
<p>&quot;Open the book element and gather all instances of titles that fall within those chapters. Then, look into the resulting object and print the contents of the first occurrence.&quot;</p>
<p>There are at least two libaries that you can install and use to bring some sanity to complex XML structures, one of which is <code>untangle</code>.</p>
<h2 id="untangle">Untangle</h2>
<p>With <code>untangle</code>, each element in an XML document gets converted into a class, which you can then probe for information. Makes no sense? well, follow along and it will become clear:</p>
<p>First, ingest the XML document. Assuming it's called <code>sample.xml</code> and is located in the current directory:</p>
<pre><code>&gt;&gt;&gt; import untangled
&gt;&gt;&gt; data = untangle.parse(&#39;sample.xml&#39;)</code></pre>
<p>Now our simple XML sample is sitting in RAM, as a Python class. The first element is <code>&lt;book&gt;</code> and all it contains is more elements, so its results are not terribly exciting:</p>
<pre><code>&gt;&gt;&gt; data.book
Element(name = book, attributes = {}, cdata = )</code></pre>
<p>As you can see, it <em>does</em> identify itself as &quot;book&quot; (under the <em>name</em> listing) but otherwise, not much to look at. That's OK, we can keep drilling down:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter
Element(name = chapter, attributes = {&#39;id&#39;: &#39;prologue&#39;}, cdata = )</code></pre>
<p>Now things get more interesting. The next element identifies itself as &quot;chapter&quot;, and reveals that it has an attribute &quot;id&quot; which has a value of &quot;prologue&quot;. To continue down this path:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter.title
Element(name = title, attributes = {}, cdata = The Beginning )</code></pre>
<p>And now we have a pretty complete picture of our little XML document. We have a breadcrumb trail of where we are in the form of the class we are invoking (<code>data.book.chapter.title</code>) and we have the contents of our current position.</p>
<h3 id="sniping">Sniping</h3>
<p>That's very linear; if you know your XML schema (and you usually do, since XML is quite strict) then you can grab values without all the walking. For instance, we know that our chapters have 'id' attributes, so we can ask for exactly that:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter[&#39;id&#39;]
&#39;prologue&#39;</code></pre>
<p>You can also get the contents of elements by looking at the <code>cdata</code> component of the class. Depending on the formatting of your document, <code>untangle</code> may be a little too literal with how it stores contents of elements, so you may want to use <code>.strip()</code> to prettify it:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter.title.cdata.strip()
&#39;The Beginning&#39;</code></pre>
<h3 id="dealing-with-more-than-one-element">Dealing with More Than One Element</h3>
<p>My example so far is nice and tidy, with only one chapter in the book. Generally you'll be dealing with more data than that. Let's add another chapter to our sample file, and some content to each:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;book&gt;
   &lt;chapter id=&quot;prologue&quot;&gt;
      &lt;title&gt;
     The Beginning
  &lt;/title&gt;
      &lt;para&gt;
     This is the first paragraph.
      &lt;/para&gt;
    &lt;/chapter&gt;

    &lt;chapter id=&quot;end&quot;&gt;
      &lt;title&gt;
     The Ending
  &lt;/title&gt;
      &lt;para&gt;
     Last para of last chapter.
      &lt;/para&gt;
    &lt;/chapter&gt;
&lt;/book&gt;</code></pre>
<p>Accessing each chapter is done with index designations, just like with a <code>dict</code>:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter[0]
Element(name = chapter, attributes = {&#39;id&#39;: &#39;prologue&#39;}, cdata = )
&gt;&gt;&gt; data.book.chapter[1]
Element(name = chapter, attributes = {&#39;id&#39;: &#39;end&#39;}, cdata = )</code></pre>
<p>If there is more than one instance of a tag, you <em>must</em> use a designator or else <code>untangle</code> won't know what to return. For example, if we want to access either the <code>title</code> or <code>para</code> elements within a chapter:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter.title
Traceback (most recent call last):
File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
AttributeError: &#39;list&#39; object has no attribute &#39;title&#39;</code></pre>
<p>Oops. But if we tell it which one to look at:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter[0].title.cdata.strip()
&#39;The Beginning&#39;
&gt;&gt;&gt; data.book.chapter[1].title.cdata.strip()
&#39;The Ending&#39;</code></pre>
<p>Or you can look at the paragraph instead of the title. The lineage is the same, only instead of looking at the <code>title</code> child, you look at the <code>para</code> child:</p>
<pre><code>&gt;&gt;&gt; data.book.chapter[0].para.cdata.strip()
&#39;This is the first paragraph.&#39;
&gt;&gt;&gt; data.book.chapter[1].para.cdata.strip()
&#39;Last para of last chapter.&#39;</code></pre>
<p>You can also iterate over items:</p>
<pre><code>&gt;&gt;&gt; COUNT = [0,1]
&gt;&gt;&gt; for TICK in COUNT:
...     print(data.book.chapter[TICK])
Element &lt;chapter&gt; with attributes {&#39;id&#39;: &#39;prologue&#39;} and children
[Element(name = title, attributes = {}, cdata = The Beginning ),
Element(name = para, attributes = {}, cdata = This is the first paragraph.)]

Element &lt;chapter&gt; with attributes {&#39;id&#39;: &#39;end&#39;} and children
[Element(name = title, attributes = {}, cdata = The Ending ),
Element(name = para, attributes = {}, cdata = Last para of last chapter.)]</code></pre>
<p>And so on.</p>
<h3 id="easy-and-fast">Easy and Fast</h3>
<p>I'll admit the data structure of the classes does look odd, and you could probably argue it's not the cleanest and most elegant of all output; it's unnerving to see empty <code>cdata</code> fields or to constantly run into the need to <code>strip()</code> whitespace. However, the ease and speed and intuitiveness of parsing XML with <code>untangle</code> is usually well worth any trade-offs.</p>
<p>[EOF]</p>
<p>Made on Free Software.</p>
