Python Parsing XML - if element == "value" do x
<p>sorry if title isn't that clear, I'm currently parsing a xml file that has lots of nested tags,  for example it goes:</p>

<pre><code>&lt;Artifacts&gt;
 &lt;Artifact name="1"&gt;
  &lt;Fragments&gt;
   &lt;hits&gt;
    &lt;hit sequence="1"&gt;
     &lt;Fragment name="1"&gt;Data&lt;/Fragment&gt;
     &lt;Fragment name="2"&gt;Data&lt;/Fragment&gt;
    &lt;/hit&gt;
   &lt;/hits&gt;
  &lt;/Fragments&gt;
 &lt;/Artifact&gt;
 &lt;Artifact name="2"&gt;
</code></pre>

<p>(Making layout a bit clearer sorry)
and so on. The pain I'm currently having is to be able to get only the data we need. From the example above we require everything under Artifact name=1, and to pull out the fragment name of "1" along with Data. The outcome aimed for would be something like:</p>

<p>Artifact = "1", Fragment Name = "1", Fragment Data = "Data".</p>

<p>At present I just can't seem to get to grips with it, I've done similar with PHP without issues but this is required to be done in python really. </p>

<p>So bit long winded sorry, but does anyone have any ideas how to specify to only grab the data from the artifacts named 1,3,5 for example and ignore everything else? All I can seem to do is grab it from everything in the file (which slows it down and then requires further processing)</p>

<p>thanks.</p>

<p>With minidom:</p>

<pre><code>from xml.dom import minidom

xmlstr = '''
&lt;Artifacts&gt;
&lt;Artifact name="1"&gt;
&lt;Fragments&gt;
&lt;Fragment name="1"&gt;Data&lt;/Fragment&gt;
&lt;/Fragments&gt;
&lt;/Artifact&gt;
&lt;Artifact name="2"&gt;
&lt;/Artifact&gt;
&lt;/Artifacts&gt;
'''


def with_children(tag):
    if tag.localName: # if not, it's text node
        print tag.localName,
        if tag.hasAttributes():
            for item in tag.attributes.items():
                print "%s=%s" % item,

        for child in tag.childNodes:
            with_children(child)

    else:
        s = tag.nodeValue.strip()
        print "data=%s" % s if s else "",

xml = minidom.parseString(xmlstr)
tags = xml.getElementsByTagName('Artifact')
tag = [t for t in tags if t.attributes['name'].value == '1'][0]
with_children(tag)
</code></pre>

python xml