Serialize XML processing instruction before root e

2019-09-01 02:18发布

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());

and I use this to serialize it:

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();

As output I get:

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

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.

P.S. I use Java 1.6.0_27 DOM. If above looks like a bug, links to bug reports are welcomed.

enter image description here

1条回答
可以哭但决不认输i
2楼-- · 2019-09-01 03:00

Xerces 2.11.0 has the expected behavior, so it is a bug that is fixed (couldn't find a bug report, though).

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);

It will preserve the node order.

查看更多
登录 后发表回答