Create an XmlElement

Procedure

  1. To create a basic XmlElement, decide the element name that you want to use.
  2. In a new expression, pass the element name to the constructor as either a QName object or a String. For example, the following line passes the name as a String:
    var el = new XmlElement("Root")

    In this case, the el.TypeInstance property returns an instance of the default type gw.xsd.w3c.xmlschema.types.complex.AnyType. If you instantiate a type instance, typically you would use a more specific subclass of AnyType, either an XSD-based type or a simple type.

  3. Optionally set attributes.
  4. Optionally add child elements by calling the addChild method with a reference to a child element.

Example

The following Gosu code creates a new XmlElement without an XSD, and then adds child elements:

uses gw.xml.XmlElement
uses javax.xml.namespace.QName

// Create parent element
var xe = new XmlElement(new QName("http://mycompany.com/schema/vehiclexsd", "root", "veh"))

// Create child elements
var xe2 = new XmlElement(new QName("http://mycompany.com/schema/vehiclexsd", "childelement", "veh"))
xe.addChild(xe2)
var xe3 = new XmlElement("childelementWithNoNamespace") // no namespace for this element
xe.addChild(xe3)

// Print element
xe.print()
print("Namespace of xe = " + xe.$Namespace)
print("Namespace of xe2 = " + xe2.$Namespace)
print("Namespace of xe3 = " + xe3.$Namespace)

This code prints the following lines:

<?xml version="1.0"?>
<veh:root xmlns:veh="http://mycompany.com/schema/vehiclexsd">
  <veh:childelement/>
  <childelementWithNoNamespace/>
</veh:root>
Namespace of ex = {http://mycompany.com/schema/vehiclexsd}
Namespace of e2 = {http://mycompany.com/schema/vehiclexsd}
Namespace of e3 = {}

What to do next

See also