views:

1399

answers:

1

I'm trying to specify a namespace using lxml similar to this example (taken from here):

<TreeInventory xsi:noNamespaceSchemaLocation="Trees.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;"&gt;
</TreeInventory>

I'm not sure how to add the Schema instance to use and also the Schema location. The documentation got me started, by doing something like:

>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'
>>> TREE = '{%s}' % NS
>>> NSMAP = {None: NS}
>>> tree = etree.Element(TREE + 'TreeInventory', nsmap=NSMAP)
>>> etree.tostring(tree, pretty_print=True)
'<TreeInventory xmlns="http://www.w3.org/2001/XMLSchema-instance"/&gt;\n'

I'm not sure how to specify it an instance though, and then also specify a location. It seems like this can be done with the nsmap keyword-arg in etree.Element, but I don't see how.

+2  A: 

In some more steps, for clarity:

>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'

As far as I can see, it is the attribute noNameSpaceSchemaLocation that you want namespaced, not the TreeInventory element. So:

>>> location_attribute = '{%s}noNameSpaceSchemaLocation' % NS
>>> elem = etree.Element('TreeInventory', attrib={location_attribute: 'Trees.xsd'})
>>> etree.tostring(elem, pretty_print=True)
'<TreeInventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Trees.xsd"/>\n'

This looks like what you wanted... You could of course also create the element first, without attributes, and then set the attribute, like this:

>>> elem = etree.Element('TreeInventory')
>>> elem.set(location_attribute, 'Trees.xsd')

As for the nsmap parameter: I believe it is only used to define which prefixes to use on serialization. In this case, it is not needed, because lxml knows the commonly used prefix for the namespace in question is "xsi". If it were not some well-known namespace, you would probably see prefixes like "ns0", "ns1" etc..., unless you specified which prefix you preferred. (remember: the prefix is not supposed to matter)

Just small correction: Should be noNamespaceSchemaLocation, no noNameSpaceSchemaLocation.
Vojtech R.