8

I have done a fair amount of reading on QName but I can't find any good examples of how to use it. Could someone give me a simple example of how to use QName and explain what context it would be used in?

Lambda Fairy
  • 13,814
  • 7
  • 42
  • 68
Michael
  • 401
  • 4
  • 9

1 Answers1

17

QName can be used when constructing XML documents with attributes that are in a different namespace than the containing element. Example (Python 2.7):

from xml.etree import ElementTree as ET

NS1 = "http://example1.com" 
NS2 = "http://example2.com"

ET.register_namespace("x", NS1) 
ET.register_namespace("y", NS2)

qname1 = ET.QName(NS1, "root")    # Element QName 
qname2 = ET.QName(NS2, "attr")    # Attribute QName

root = ET.Element(qname1, {qname2: "test"}) 
print ET.tostring(root)

Output:

<x:root xmlns:x="http://example1.com" xmlns:y="http://example2.com" y:attr="test" />

One application for which this can be useful is XLink.

mzjn
  • 48,958
  • 13
  • 128
  • 248
  • More examples: https://stackoverflow.com/q/46405690/407651, https://stackoverflow.com/q/58642263/407651 – mzjn Nov 15 '21 at 17:44