namespace – Handle XML namespaces

Handle XML namespaces.

The library.namespace module manage XML name by expanding or shortening name based on namespaces. It is mainly used to keep XML name in a short form to smooth the name of metadata or image adjustment in report or source code.

Using namespace

For this short tutorial, we have a dummy XML document which use the namespace http://ns.nikon.com/nine/1.0/ associated to the nine prefix used as sample.

Listing 2 XML dummy document
 <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
     <rdf:Description rdf:about=""
                      xmlns:nine="http://ns.nikon.com/nine/1.0/">
         <nine:about>nine-tags</nine:about>
         <nine:version>2.0.0</nine:version>
     </rdf:Description>
 </rdf:RDF>

We create an instance of NameSpace with the pair prefix, URI as declared with xmlns attribute (here nine= “http://ns.nikon.com/nine/1.0/”). This pair is expressed as a dictionnary with the prefix as key.

>>> from library.namespace import NameSpace
>>> ns = NameSpace({"nine": "http://ns.nikon.com/nine/1.0/"})

We can expand or shorten the XML name.

>>> ns.expand_name("nine:about")
'{http://ns.nikon.com/nine/1.0/}about'
>>> ns.shorten_name("{http://ns.nikon.com/nine/1.0/}about")
'nine:about'

Reference

class darkbridge.library.namespace.NameSpace(namespaces: dict)

Bases: object

XML Namespace basic tools.

This class offers method to shorten or expand XML name base on a namespace dictionary.

Parameters:

namespaces – Dictionary containing the nanapace prefix and assiocted namespace uri as defined in xmlns attribute. Example: {"nine": "http://ns.nikon.com/nine/1.0/"}

shorten_name(name: str) str

Shorten a tag or attribute name based on the namespace table.

Parameters:

name – Name of the tag or attribute in expanded format (i.e. {uri}tag). An empty string or without uri is accepted.

Returns:

Name in a short format (i.e. prefix:tag). An empty string or without uri in expanded_name returns the unchanged value.

expand_name(name: str) str

Expand a tag or attribute name based on the namespace table.

Parameters:

name – Name of the tag or attribute in short format (i.e. prefix:tag). An empty string or without prefix is accepted.

Returns:

Name in expanded format (i.e. {uri}tag). An empty string or without prefix in short_name return the unchanged value.