使 JAXB 生成 XML 处理指令 [英] Making JAXB generate an XML processing instruction

查看:33
本文介绍了使 JAXB 生成 XML 处理指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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 中,我们需要使用属性键作为 com.sun.xml.internal.bind.xmlHeaders,如下所示.

In recent version of JAXB we need to use property key as com.sun.xml.internal.bind.xmlHeaders like below.

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

这篇关于使 JAXB 生成 XML 处理指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆