【问题标题】:Format attributes for XML in Pretty format in java在java中以Pretty格式格式化XML的属性
【发布时间】: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。

标签: java xml dom sax


【解决方案1】:

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

【讨论】:

  • 我不想仅仅为一个小功能创建客户解析器,但应该有标志来禁用此行为或线宽变量。你知道什么吗?
  • 我不知道明确的线宽特征。但另一方面,填充一个接口比实际创建解析器要少得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多