2011-11-02 54 views
0

我有下面的代码,即插入根元素之前的处理操作的指令:序列化XML处理指令

Document doc = builder.parse(file); 

doc.insertBefore(
      doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"annotation.xsl\""), 
      doc.getDocumentElement()); 
doc.insertBefore(doc.createProcessingInstruction("oxygen", "NVDLSchema=\"annotation.nvdl\""), 
      doc.getDocumentElement()); 

和我使用它来序列化:

FileOutputStream fos = new FileOutputStream(new File(file.getAbsolutePath() + ".out")); 
DOMImplementationLS ls = (DOMImplementationLS) builder.getDOMImplementation(); 

LSOutput lso = ls.createLSOutput(); 
lso.setByteStream(fos); 
ls.createLSSerializer().write(doc, lso); 

fos.close(); 

作为输出I得到:

<?xml version="1.0" encoding="UTF-8"?> 
<fulltext-document>...</fulltext-document><?xml-stylesheet type="text/xsl" href="annotation.xsl"?><?oxygen NVDLSchema="annotation.nvdl"?> 

但是我打算有处理指令之前根元素。我检查了可能是DOM三不正确(见下文),但一切看起来都不错。有什么我错过了吗?欢迎任何解决方案。

P.S.我使用Java 1.6.0_27 DOM。如果上面看起来像一个错误,欢迎链接到错误报告。

enter image description here

回答

2

的Xerces 2.11.0有预期的行为,所以它是修正了一个错误(找不到错误报告,虽然)。

如果您必须使用JDK版本,而不是使用LSSerializer,则可以使用标识转换。

Transformer t = TransformerFactory.newInstance().newTransformer(); 
    t.transform(new DOMSource(doc), new StreamResult(fos); 

它将保留节点顺序。

+0

谢谢你的优雅的解决方案。 –