Reputation: 334
I am trying to build an XML file in which my main node has some attributes:
<cbnp-message:cbnp-message xmlns:cbnp-message="some_value" xmlns="some_value2">
I am trying to achieve that using Python3 and lxml library and so far I managed to set xmlns parameter for some_value2. What I can't do I to set cnbp-message:cnbp-message thing (sorry for my lack of proper naming: I am not working with XMLs on daily basis).
What is tricky here and prevents me from hard-coding such informations before creating XML file is that ending tag of aforementioned XML has to end with
</cbnp-message:cnbp-message>
I would appreciate all ideas and suggestion how to tackle such task.
I already tried creating a node with cnbp-message:cbnp-message name, it doesn't work though (raises ValueError: Invalid tag name exception)
Upvotes: 1
Views: 487
Reputation: 52858
Those aren't normal attributes; those are namespace declarations.
This declaration: xmlns:cbnp-message="some_value"
binds the namespace uri some_value
to the prefix cbnp-message
.
This declaration: xmlns="some_value2"
is a default namespace (since the uri is not bound to a prefix).
What you can do in lxml is use "nsmap" to map prefixes to uris. For default namespaces the prefix should be None
.
To avoid the "Invalid tag name" exception, you'll also need to use QName()
to build the qualified name (which is the namespace uri and local name in Clark Notation (example: {some_value}cbnp-message
)).
See here for more info on namespaces in lxml.
See here (or the link to James Clark's page above) for more info on namespaces in general.
Example...
from lxml import etree
nsmap = {None: "some_value2", "cbnp-message": "some_value"}
message = etree.Element(etree.QName(nsmap.get("cbnp-message"), "cbnp-message"), nsmap=nsmap)
etree.dump(message)
Output...
<cbnp-message:cbnp-message xmlns:cbnp-message="some_value" xmlns="some_value2"/>
Upvotes: 1