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>
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
Igor Tischenko
  • 620
  • 9
  • 20
  • Please see the following: https://stackoverflow.com/questions/38349579/python-elementtree-does-not-like-colon-in-name-of-processing-instruction – Jimmy Lee Jones Mar 28 '18 at 14:55

1 Answers1

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")
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
  • this will add a xmlns: to tag, I don't need it. – Igor Tischenko Mar 28 '18 at 19:15
  • 1
    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 – Mads Hansen Mar 28 '18 at 19:26