tags:

views:

26

answers:

2

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

A: 

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>
McDowell
A: 

Use "write*" instead of "set*"

javax.xml.stream.XMLStreamWriter.writeDefaultNamespace(String)
mrrtnn
Hi, Martin; thanks, but the question was about XMLEventWriter, not XMLStreamWriter.
Laird Nelson