get attribute from xml-node with specific value
<p>I have an XSD-file where I need to get a namespace as defined in the root-tag:</p>

<pre><code>&lt;schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:abw="http://www.liegenschaftsbestandsmodell.de/ns/abw/1.0.1.0" xmlns:adv="http://www.adv-online.de/namespaces/adv/gid/6.0" xmlns:bfm="http://www.liegenschaftsbestandsmodell.de/ns/bfm/1.0" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:sc="http://www.interactive-instruments.de/ShapeChange/AppInfo" elementFormDefault="qualified" targetNamespace="http://www.liegenschaftsbestandsmodell.de/ns/abw/1.0.1.0" version="1.0.1.0"&gt;
  &lt;!-- elements --&gt;
&lt;/schema&gt;
</code></pre>

<p>Now as the <code>targetNamespace</code> of this schema-definition is <code>"http://www.liegenschaftsbestandsmodell.de/ns/abw/1.0.1.0"</code> I need to get the short identifier for this namespace - which is <code>abw</code>. To get this identifier I have to get that attribute from the root-tag that has the exact same value as my <code>targetNamespace</code> (I canÂ´t rely on the identifier beeing part of the <code>targetNamespace</code>-string allready, this may change in the future). </p>

<p>On this question <a href="http://stackoverflow.com/questions/4573237/how-to-extract-xml-attribute-using-python-elementtree">How to extract xml attribute using Python ElementTree</a> I found how to get the value of an attribute given by its name. However I donÂ´t know the attributes name, only its value, so what can I do when I have a value and want to select the attribute having this value?</p>

<p>I think of something like this:</p>

<pre><code>for key in root.attrib.keys():
    if(root.attrib[key] == targetNamespace):
        return root.attrib[key]
</code></pre>

<p>but <code>root.attrib</code> only contains <code>elementFormDefault</code>, <code>targetNamespace</code> and <code>version</code>, but not <code>xmlns:abw</code>. </p>

<p>Using minidom instead of ETree did it:</p>

<pre><code>import xml.dom.minidom as DOM
tree = DOM.parse(myFile)
root = tree.documentElement
targetNamespace = root.getAttribute("targetNamespace")

d = dict(root.attributes.items())
for key in d:
    if d[key] == targetNamespace: return key
</code></pre>

<p>This will return either <code>targetNamespace</code> or <code>xmlns:abw</code> depending on what comes first in the xsd. Of course we should ignore the first case, but this goes out of scope of this question.</p>

python xml