问题描述
我使用JAXB动态生成XML。
I am generating XML dynamically using JAXB.
现在,我想使用XSL将其转换为HTML。我该如何包含
Now, I want to convert it to HTML using XSL. How can i include
<?xml-stylesheet type="text/xsl" href="">
动态生成的XML中的
?
in the dynamically generated XML?
推荐答案
这里的所有解决方案都非常丑陋且冗长。只需在 Mashaller
对象中设置指定附加标题的行。
All the solutions here are pretty ugly and verbose. Simply set the line inside the Mashaller
object specifying the additional header.
Marshaller jaxbMarshaller = ...
jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders",
"<?xml-stylesheet type='text/xsl' href='nameoffile.xsl' ?>");
此示例将使用样式表将XML对象输出到文件,并将元素很好地格式化为人类读。对象 myXmlObject
属于类 MyXmlClass
,并将写入 file
,由 xslUrl
给出的样式表格式化:
This example will output an XML object to a file using a stylesheet and format the elements nicely for humans to read. The object myXmlObject
is of class MyXmlClass
, and will be written to file
, formatted by a stylesheet given by 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);
这篇关于使JAXB生成XML处理指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!