Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Inclusion of unused namespace declarations in marshalled XML

Mark Hagan-OracleNov 4 2010 — edited Nov 5 2010
Hello.

I have noticed that by default any XML marshaled from an object contains namespace declarations related to every package specified when instantiating the JAXBContext even though they are not used in the instance being marshalled.

Is there any way to avoid this during the marshalling as opposed to via some sort of post processing (e.g. XSLT transform).

Example source below:
package test;

import javax.xml.bind.*;
import java.io.*;

import test.sample1.*;
import test.sample2.*;

public class Converter {

	public static void main(String[] args) {
		try {
			String sample1 = "<Message1 xmlns=\"http://www.example.org/sample1\">" +
							 	"<tns:Field xmlns:tns=\"http://www.someother.org\">value</tns:Field>" +
							 "</Message1>";
			String sample2 = "<Message2 xmlns=\"http://www.example.org/sample2\">" +
							     "<Field1>value1</Field1>" +
							     "<Field2>value2</Field2>" +
							 "</Message2>";
			
			JAXBContext ctx = JAXBContext.newInstance("test.sample1:test.sample2");
			
			Unmarshaller um = ctx.createUnmarshaller();
			Marshaller m = ctx.createMarshaller();

			StringWriter sw1 = new StringWriter(); 			
			Message1 msg = (Message1)um.unmarshal(new StringReader(sample1));
			m.marshal(msg, sw1);			
			System.out.println("Marshalled sample1: \n"+sw1.toString());
			
			StringWriter sw2 = new StringWriter(); 			
			Message2 msg2 = (Message2)um.unmarshal(new StringReader(sample2));
			m.marshal(msg2, sw2);			
			System.out.println("Marshalled sample2: \n"+sw2.toString());
			
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}
Produces output:-
Marshalled sample1:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Message1 xmlns:ns2="http://www.example.org/sample2" xmlns="http://www.example.org/sample1"><tns:Field xmlns:tns="http://www.someother.org">value</tns:Field></Message1>
Marshalled sample2:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:Message2 xmlns:ns2="http://www.example.org/sample2" xmlns="http://www.example.org/sample1"><ns2:Field1>value1</ns2:Field1><ns2:Field2>value2</ns2:Field2></ns2:Message2>
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 3 2010
Added on Nov 4 2010
4 comments
1,616 views