5

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

pnuts
  • 58,317
  • 11
  • 87
  • 139
Laird Nelson
  • 15,321
  • 19
  • 73
  • 127
  • I should mention that I can get it emitted if I add it as an explicit Namespace, and construct an Iterator that includes that Namespace, and call the most-parameterized version of XMLEventFactory#createStartElement(). But I would have thought XMLWriter.setDefaultNamespace() would have done *something*. I don't see that it has any effect at all. – Laird Nelson Jun 25 '10 at 16:20

2 Answers2

4

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
  • 107,573
  • 31
  • 204
  • 267
  • 2
    What if I'm reading an element in from an XMLEventReader and then writing it with the XMLEventWriter, and need to add the namespace to a certain element, not creating an event with createStartElement? How can I add a namespace then? – k-den Jul 09 '19 at 03:57
-1

Use "write*" instead of "set*"

javax.xml.stream.XMLStreamWriter.writeDefaultNamespace(String)
Martín Schonaker
  • 7,273
  • 4
  • 32
  • 55