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? XML开发者_开发百科EventWriter.setDefaultNamespace() didn't work.
Thanks, Laird
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>
Use "write*" instead of "set*"
javax.xml.stream.XMLStreamWriter.writeDefaultNamespace(String)
精彩评论