Tuesday, 18 October 2016

XML : get attribute from xml-node with specific value

I have an XSD-file where I need to get a namespace as defined in the root-tag:

  <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">    <!-- elements -->  </schema>    

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

On this question How to extract xml attribute using Python ElementTree 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?

I think of something like this:

  for attr in root.attrib:      if(attr.value == targetNamespace):          return attr.value    

No comments:

Post a Comment