org.w3c.dom.ls.LSSerialize - 设置文本换行,缩进大小

时间:2014-02-17 19:34:04

标签: java xml xml-parsing xml-serialization xerces

我使用以下代码缩进xml文档,该文档以字符串形式提供给我。

如果重要的话,我正在使用org.w3c.dom.ls的JDK实现。

http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/package-summary.html

public String format(String xml) {

    try {
        final InputSource src = new InputSource(new StringReader(xml));
        final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
        final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

    //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");

        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();

        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.

        return writer.writeToString(document);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

有没有办法定义以下任何一项:

  • 缩进的大小
  • 是否进行文字换行,
  • 如果我想进行文字换行,最大行长

我已经尝试过查看javadocs和在线示例......但找不到任何示例。我只看到使用旧API的示例,现在已弃用。

0 个答案:

没有答案