使JAXB生成XML处理指令

时间:2010-01-28 08:42:01

标签: xml xslt jaxb

我使用JAXB动态生成XML。

现在,我想使用XSL将其转换为HTML。我怎么能包括

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

在动态生成的XML中?

4 个答案:

答案 0 :(得分:10)

这里的所有解决方案都非常丑陋且冗长。只需在Mashaller对象内设置指定附加标题的行。

Marshaller jaxbMarshaller = ...
jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders", 
    "<?xml-stylesheet type='text/xsl' href='nameoffile.xsl' ?>");

此示例将使用样式表将XML对象输出到文件,并很好地格式化元素以供人阅读。对象myXmlObject属于MyXmlClass类,将写入file,由xslUrl给出的样式表格式化:

JAXBContext context = JAXBContext.newInstance(MyXmlClass.class);
Marshaller marshaller = context.createMarshaller();
//Need to use a Writer to marshal with the XSL
FileWriter fw = new FileWriter(file);
//Do this or else the XML is all one line and not human friendly...
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty("com.sun.xml.bind.xmlHeaders",
        "<?xml-stylesheet type='text/xsl' href=\"" +
        xslUrl +
        "\" ?>");
marshaller.marshal(myXmlObject, fw);

答案 1 :(得分:4)

您可以使用StringWriter首先将样式表信息写入其中,然后将对象编组到其中:

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();

当然,您也可以直接打印到您想要的所有其他输出流,例如files或Sytstem.out。

答案 2 :(得分:2)

了解它是如何在rexsl-core中完成的,这是ReXSL XSL / JAXB / JAX-RS框架的一部分:XslResolver

final String header = String.format(
  "\n<?xml-stylesheet type='text/xsl' href='%s'?>",
  StringEscapeUtils.escapeXml("my-stylesheet.xsl")
);
marshaller.setProperty("com.sun.xml.bind.xmlHeaders", header);

答案 3 :(得分:1)

JAXBContext jaxbContext;
try {
       jaxbContext = JAXBContext.newInstance(new Class[] {SomeObject.class});

       StringWriter writer = new StringWriter();
       writer.write("<?xml version='1.0'?>");
       writer.write("\n");
       writer.write("<?xml-stylesheet type=\"text/xsl\" href=\"\">");
       writer.write("\n");

       Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
       jaxbMarshaller.marshal(someobject, writer);
}