如何解决java中漂亮格式的XML格式属性
我正在尝试将 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 库的解决方案。
解决方法
SAX 或 DOM 解析器将读取您的输入字符串并让您的应用程序了解传入的内容。在某个时间点您的应用程序会写出该数据,这就是您决定插入额外空格的时刻(像换行符和制表符)来漂亮地打印文档。
如果您真的想使用 SAX 并使解析器高效,您可以做的最好的事情就是在解析文档时编写文档。因此,您将实现 ContentHandler 接口 (https://docs.oracle.com/en/java/javase/11/docs/api/java.xml/org/xml/sax/ContentHandler.html),使其直接写出数据,同时在您认为它们所属的位置添加换行符。
查看本教程以了解如何在 SAX 解析器中应用 ContentHandler:https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。