【问题标题】:Serialize XML processing instruction before root element在根元素之前序列化 XML 处理指令
【发布时间】:2011-11-02 12:09:17
【问题描述】:

我有以下代码,在根元素之前插入处理指令:

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 三个是不正确的(见下文),但一切看起来都很好。有什么我错过的吗?欢迎任何解决方案。

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

【问题讨论】:

    标签: java xml xml-serialization


    【解决方案1】:

    Xerces 2.11.0 具有预期的行为,因此它是一个已修复的错误(但找不到错误报告)。

    如果你必须使用 JDK 版本,而不是使用 LSSerializer,你可以使用身份转换。

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

    它将保留节点顺序。

    【讨论】:

    • 感谢您提供优雅的解决方案。
    猜你喜欢
    • 2017-12-26
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 2023-03-03
    相关资源
    最近更新 更多