2

I have to add tag which contains a colon ':' symbol, but python does not like it:

The code I have is:

temp = etree.SubElement(OTHER, 'IDS:OwnedPropertyRentNetCust')
    temp.text = 'true'

It returns next error:

Invalid tag name u'IDS:OwnedPropertyRentNetCust'

How do I create an element with a colon?

Final tag has to be:

<IDS:OwnedPropertyRentNetCust>
2

1 Answer 1

3

XML elements that have the colon : are bound to a namespace and are using a namespace-prefix. The value before the : is the namespace-prefix, which is like a variable referencing a namespace value.

There are a couple of ways to create an element bound to a namespace.

Instead of a string for the element name, you can provide a QName():

from xml.etree import ElementTree as ET
IDS_NS   =  "http://whatever/the/IDS/namespace/value/is" #adjust this to the real IDS NS
ET.register_namespace("IDS", IDS_NS) 
et.SubElement(root, et.QName(IDS_NS, "OwnedPropertyRentNetCust"))

Use Clark notation, which includes the namespace and the element's local-name() in the string value:

from xml.etree import ElementTree as ET
IDS_NS   =  "http://whatever/the/IDS/namespace/value/is"
ET.register_namespace("IDS", IDS_NS) 
et.SubElement(root, "{http://whatever/the/IDS/namespace/value/is}OwnedPropertyRentNetCust")
Sign up to request clarification or add additional context in comments.

3 Comments

this will add a xmlns: to tag, I don't need it.
In order for an element to have an XML namespace prefix, it must be bound to a namespace (even if that is empty), or it must be declared on an ancestor element. If not, then it isn’t valid we’ll-formed XML and will have a hard time trying to make it with XML apis
How did you add the ':' to your xml?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.