添加xml-stylesheet并获得standalone = yes

时间:2010-04-16 08:43:34

标签: java xml xslt

我在下面的代码中添加了解决方案。

底部的代码就是我所拥有的。我删除了所有标签的创建。

在我得到的xml文件的顶部。<?xml version="1.0" encoding="UTF-8" standalone="no"?>请注意,独立是不,即使你将它设置为是。

第一个问题:我如何获得独立=是?

我想在xml文件的第二行添加<?xml-stylesheet type="text/xsl" href="my.stylesheet.xsl"?>

第二个问题:我该怎么做?

一些有用的链接?什么?

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();  
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();  
Document doc = docBuilder.newDocument();
doc.setXmlStandalone(true);
ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");

Element root = doc.createElement("root-element");
doc.appendChild(root);
doc.insertBefore(pi, root);    

<cut>  

TransformerFactory transfac = TransformerFactory.newInstance();
transfac.setAttribute("indent-number", new Integer(2));
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.STANDALONE, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "name");

FileOutputStream fout = new FileOutputStream(filepath);
BufferedOutputStream bout= new BufferedOutputStream(fout);
trans.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(bout, "utf-8")));

2 个答案:

答案 0 :(得分:11)

我添加了

doc.setXmlStandalone(true);
ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"my.stylesheet.xsl\"");`  

切割前和

doc.insertBefore(pi, root);

在将根元素附加到文档之后。

答案 1 :(得分:3)

在我的代码中,我写道:


DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlStandalone(true);

TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer transformer = tfactory.newTransformer();
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");

输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>