这里的所有解决方案都非常丑陋且冗长.只需在Mashaller对象中设置指定附加标题的行.
Marshaller jaxbMarshaller = ... jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders","<?xml-stylesheet type='text/xsl' href='nameoffile.xsl' ?>");
此示例将使用样式表将XML对象输出到文件,并且很好地格式化元素以供人类阅读.对象myXmlObject属于MyXmlClass类,将被写入文件,由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);