I am using xmlstreamwriter and jaxb in conjunction to marshall a big xml file. i am creating sub-tree with jaxb but the issue is when i marshal the sub-tree it is prefixed with default namespace as below:
<?xml version="1.0" encoding="UTF-8"?>
<MessageModel xmlns="urn:schemas.mycompany.com/ENT/MessageModel/2013/09/19">
<MessageHeader xmlns="" xmlns:ns2="urn:schemas.mycompany.com/ENT/MessageModel/2013/09/19">
<ns2:ProviderID>5922</ns2:ProviderID>
<ns2:EffectiveDT>2016-08-08-04:00</ns2:EffectiveDT>
<ns2:PartyCount>0</ns2:PartyCount>
<ns2:ArrangementCount>1</ns2:ArrangementCount>
<ns2:AppMetaDataString>ter</ns2:AppMetaDataString>
</MessageHeader>
</MessageModel>
I am using below code for marshaling:
StringWriter result = new StringWriter();
MessageHeaderType messageHeaderType = createMessageHeader(objectFactory);
JAXBElement<MessageHeaderType> element = new JAXBElement<MessageHeaderType>(new QName("MessageHeader"), MessageHeaderType.class, messageHeaderType);
XMLStreamWriter xmlOut = XMLOutputFactory.newFactory().createXMLStreamWriter(result);
**//Setting default namespace**
xmlOut.setDefaultNamespace("urn:schemas.mycompany.com/ENT/MessageModel/2013/09/19");
xmlOut.writeStartDocument();
xmlOut.writeStartElement("urn:schemas.mycompany.com/ENT/MessageModel/2013/09/19", "MessageModel");
xmlOut.writeNamespace("", "urn:schemas.mycompany.com/ENT/MessageModel/2013/09/19");
JAXBContext context = JAXBContext.newInstance(MessageHeaderType.class);
Marshaller marshaller = context.createMarshaller();
//marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(element, xmlOut);
xmlOut.writeEndDocument();
xmlOut.close();
System.out.println(result.toString());
I am setting default namespace but it still creating sub-tree with namespace. what can i do to generate sub-tree with jaxb but without namespace?
The way you used QName is incorrect, I had a similar problem when I first used it.
When you simply give the localName (one String constructor), it assumes the namespace is empty. This is why MessageHeader has a tag xmlns=""
. Read more about that here.
The constructor you should use is this.
Replace your current QName with this one and it should work:
new QName("urn:schemas.mycompany.com/ENT/MessageModel/2013/09/19", "MessageHeader");
Also, you don't need
xmlOut.writeNamespace("", "urn:schemas.mycompany.com/ENT/MessageModel/2013/09/19");
It's the same thing as the default namespace one.