在根元素之前序列化 XML 处理指令 [英] Serialize XML processing instruction before root element
问题描述
我有以下代码,在根元素之前插入处理指令:
I have the following code, that inserts the processing instructions before root element:
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();
作为输出我得到:
<?xml version="1.0" encoding="UTF-8"?>
<fulltext-document>...</fulltext-document><?xml-stylesheet type="text/xsl" href="annotation.xsl"?><?oxygen NVDLSchema="annotation.nvdl"?>
但是我打算在之前根元素有处理指令.我检查过可能 DOM 3 不正确(见下文),但一切看起来都不错.有什么我错过了吗?欢迎任何解决方案.
However I intended to have processing instructions before root element. I checked that perhaps the DOM three is incorrect (see below), but everything looks OK. Is there anything I've missed? Any solution is welcomed.
附言我使用 Java 1.6.0_27 DOM.如果以上看起来像一个错误,欢迎链接到错误报告.
P.S. I use Java 1.6.0_27 DOM. If above looks like a bug, links to bug reports are welcomed.
推荐答案
Xerces 2.11.0 具有预期的行为,因此它是一个已修复的错误(但找不到错误报告).
Xerces 2.11.0 has the expected behavior, so it is a bug that is fixed (couldn't find a bug report, though).
如果必须使用 JDK 版本,则可以使用身份转换,而不是使用 LSSerializer.
If you have to use the JDK version, instead of using the LSSerializer, you can use an identity transformation.
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(doc), new StreamResult(fos);
它将保留节点顺序.
这篇关于在根元素之前序列化 XML 处理指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!