【发布时间】:2021-09-30 00:24:15
【问题描述】:
我正在尝试将 XML 字符串格式化为漂亮。我希望所有属性都打印在单行中。 XML 输入:
<root><feeds attribute1="a" attribute2="b" attribute3="c" attribute4="d" attribute5="e" attribute6="f"> <id>2140</id><title>gj</title><description>ghj</description>
<msg/>
预期输出:
<root>
<feeds attribute1="a" attribute2="b" attribute3="c" attribute4="d" attribute5="e" attribute6="f">
<id>2140</id>
<title>gj</title>
<description>ghj</description>
<msg/>
</feeds>
实际输出:
<root>
<feeds attribute1="a" attribute2="b" attribute3="c" attribute4="d"
attribute5="e" attribute6="f">
<id>2140</id>
<title>gj</title>
<description>ghj</description>
<msg/>
</feeds>
这是我格式化 xml 的代码。我也尝试过 SAX 解析器。我不想使用 DOM4J。
public static String formatXml(String xml) {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", false);
writer.getDomConfig().setParameter("well-formed", true);
LSOutput output = impl.createLSOutput();
ByteArrayOutputStream out = new ByteArrayOutputStream();
output.setByteStream(out);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
writer.write(db.parse(is), output);
return new String(out.toByteArray());
}
有什么方法可以用 SAX 或 DOM 解析器将属性保持在一行中?我不是在寻找任何额外的图书馆。我正在寻找仅使用 java 库的解决方案。
【问题讨论】:
-
format-pretty-print的真正含义取决于序列化程序的实现。在这种情况下,它“可能”与输出的线宽有关,但确实存在一个问题,因为属性的数量可以是任意的。您或许应该编写自定义格式化程序或使用 xslt。 -
应该有一个属性来定义单个元素中的字符数,或者一个标志来禁用扭曲。你知道什么吗?我检查了这个,但没有运气。 docs.oracle.com/javase/8/docs/api/org/w3c/dom/…
-
昨天看了源码没找到实现format的地方
-
我找到了解析完成的地方:
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(boolean),可能这是格式化类:com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl。