0

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

dma_k
  • 10,431
  • 16
  • 76
  • 128

1 Answers1

2

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.

forty-two
  • 12,204
  • 2
  • 26
  • 36