Creating many qualified names in the same namespace

The name of each element is a qualified name, which is an object of type javax.xml.namespace.QName.

A QName object contains the following parts:

  • A namespace URI
  • A local part
  • A suggested prefix for this namespace.

    On serialization of an XmlElement, Gosu tries to use the prefix to generate the name, such as "wsdl:definitions". In some cases however, it might not be possible to use this name. For example, if an XML element defines two attributes with different namespaces but the same prefix. On serialization, Gosu auto-creates a prefix for one of them to prevent conflicts.

Typical code repetitively creates many QName objects in the same namespace. One way to create many such objects is to store the namespace URI in a String variable, then create QName instances with new local parts.

To simplify this process, Gosu includes a utility class called gw.xml.XmlNamespace. It represents a namespace URI and a suggested prefix. In other words, it is like a QName but without the local part.

There are two ways to use XmlNamespace:

  • Create an XmlNamespace directly and call its qualify method and pass the local part String. For example:
    uses gw.xml.XmlNamespace
    var ns = new XmlNamespace("namespaceURI","prefix")
    var ex = new XmlElement(ns.qualify("localPartName"))
  • Reuse the namespace of an already-created XML element. To get the namespace from an XML element instance, get its NameSpace property. Then, call the qualify method and pass the local part String:
    // Create a new XML element.
    var xml = new XmlElement(new QName("namespaceURI", "localPart", "prefix"))
    
    // Reuse the namespaceURI and prefix from the previously created element.
    var xml2 = new XmlElement(xml.Namespace.qualify("localPart2"))

See also