XML attribute parsing with python and ElementTree
<p>folks!
I'm trying to parse some weird formed XML:</p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;analytics&gt;
  &lt;standard1&gt;
    ...
    &lt;attributes&gt;
      &lt;attribute name="agentname" value="userx userx" /&gt;
      &lt;attribute name="agentpk" value="5" /&gt;
      &lt;attribute name="analytics:callid" value="757004000003597" /&gt;
      ...
      &lt;attribute name="wrapuptime" value="0" /&gt;
    &lt;/attributes&gt;
  &lt;/standard1&gt;
  &lt;standard2&gt;
    ...
    &lt;attributes&gt;
      &lt;attribute name="agentname" value="userx userx" /&gt;
      &lt;attribute name="agentpk" value="5" /&gt;
      &lt;attribute name="analytics:callid" value="757004000003597" /&gt;
      ...
      &lt;attribute name="wrapuptime" value="0" /&gt;
    &lt;/attributes&gt;
  &lt;/standard2&gt;
  &lt;engines&gt;
  ...
  &lt;/engines&gt;
&lt;/analytics&gt;
</code></pre>

<p>Since both <em>name</em> and <em>value</em> are attributes, I have no idea how to access <em>value</em> by <em>name</em> without looping through the whole attributes subsection with a foreach cycle.</p>

<p>Any ideas how to get a direct access using ElementTree?</p>

<p>You can use a simple <em>XPath expression</em> to filter <code>attribute</code> element by the value of <code>name</code> attribute. Sample working code:</p>

<pre><code>import xml.etree.ElementTree as ET

data = """&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;analytics&gt;
  &lt;standard&gt;
      &lt;attributes&gt;
        &lt;attribute name="agentname" value="userx userx" /&gt;
        &lt;attribute name="agentpk" value="5" /&gt;
        &lt;attribute name="analytics:callid" value="757004000003597" /&gt;
        &lt;attribute name="wrapuptime" value="0" /&gt;
      &lt;/attributes&gt;
  &lt;/standard&gt;
&lt;/analytics&gt;
"""

root = ET.fromstring(data)
print(root.find(".//attribute[@name='agentname']").attrib["value"])
</code></pre>

<p>Prints:</p>

<pre><code>userx userx
</code></pre>

<p>Beware that <code>xml.etree.ElementTree</code> has a <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support" rel="nofollow">limited XPath support</a>.</p>

python xml elementtree