1

I´m using JAXB to marshall an Java object to XML.

I want to make a web service where i put this code and return the xml, but the last line where i do the marshall doesn´t return a string because it´s a handler.

    JAXBContext context = JAXBContext.newInstance(Person.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Person person = new Person("Anonymous", 32, "employee");    

    marshaller.marshal(person, System.out);

Has anyone done this before?

bruno
  • 2,154
  • 5
  • 39
  • 64

3 Answers3

1

You could marshal to a StringWriter instead.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
1

The marshaller.marshal() has several overriden methods that allow you to marshal an object into an outputstream, File, w3c.dom.Node ... etc.

The better question might be what are you using to write the web service. If you are using JAX-WS, these things are done automatically for you.

http://jaxb.java.net/nonav/2.2.3/docs/api/javax/xml/bind/Marshaller.html

Kal
  • 24,724
  • 7
  • 65
  • 65
0

Just a comment, JAXBContext.newInstance needs to be cached, as it can be very expensive.

http://app-inf.blogspot.com/2012/10/performance-tuning-logging-right-way.html

How do I improve performance of application that uses the JAXBContext.newInstance operation?

Community
  • 1
  • 1