Search code examples
javaxmlxml-namespacesstax

XMLEventWriter from scratch: how do I emit xmlns attribute?


I am trying to write an XML document from scratch using the XMLEventWriter from the StAX API.

I cannot figure out how to get the default namespace attribute to be emitted.

For example, the default namespace URI string is "http://www.liquibase.org/xml/ns/dbchangelog/1.9". I want that to be present in my XML root element as xmlns="http://www.liquibase.org/xml/ns/dbchangelog/1.9".

What's the magic recipe here? XMLEventWriter.setDefaultNamespace() didn't work.

Thanks, Laird


Solution

  • Use the property IS_REPAIRING_NAMESPACES to set this behaviour:

    XMLEventFactory events = XMLEventFactory.newInstance();
    QName bar = new QName("urn:bar", "bar");
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    XMLEventWriter writer = factory.createXMLEventWriter(System.out);
    writer.add(events.createStartDocument());
    writer.setDefaultNamespace("urn:bar");
    writer.add(events.createStartElement(bar, null, null));
    writer.add(events.createEndDocument());
    writer.flush();
    

    The above code emits:

    <?xml version="1.0"?><bar xmlns="urn:bar"></bar>