我正在使用JAXB动态生成XML.
现在,我想使用XSL将其转换为HTML.我怎么能包括
<?xml-stylesheet type="text/xsl" href="">
Run Code Online (Sandbox Code Playgroud)
在动态生成的XML中?
mat*_*boy 11
这里的所有解决方案都非常丑陋和冗长.只需在Mashaller对象内设置指定附加标题的行.
Marshaller jaxbMarshaller = ...
jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders",
"<?xml-stylesheet type='text/xsl' href='nameoffile.xsl' ?>");
Run Code Online (Sandbox Code Playgroud)
此示例将使用样式表将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);
Run Code Online (Sandbox Code Playgroud)
您可以使用 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();
Run Code Online (Sandbox Code Playgroud)
当然,您也可以直接打印到您想要的每个其他输出流,例如文件或 Sytstem.out。
| 归档时间: |
|
| 查看次数: |
7139 次 |
| 最近记录: |