tags:

views:

218

answers:

1

I am generating XML dynamically using JAXB.

Now, I want to convert it to HTML using XSL. How can i include

<?xml-stylesheet type="text/xsl" href=""> 

in the dynamically generated XML?

A: 

You could use a StringWriter to first write the stylesheet information into it, and then marshal the object into it:

StringWriter writer = new StringWriter();
//add processing instructions "by hand" with escaped quotation marks
//or single marks
writer.println("<?xml version='1.0'?>");
writer.println("<?xml-stylesheet type=\"text/xsl\" href=\"\">");

//create and configure marshaller to leave out processing instructions
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

//marshal to the StringWriter
marshaller.marshal(someObject,writer);
//get the string representation 
String str = writer.toString();

Of course you can also directly print to every other output stream you want, e.g. files or Sytstem.out.

Jasper