Java 中的 StAX XML 格式化
是否可以使用StAX(特别是woodstox)使用换行符和制表符来格式化输出xml,即采用以下形式:
<element1> <element2> someData </element2> </element1>
而不是:
<element1><element2>someData</element2></element1>
如果这在woodstox中不可能,是否有其他轻量级库可以做到这一点?
Is it possible using StAX (specifically woodstox) to format the output xml with newlines and tabs, i.e. in the form:
<element1> <element2> someData </element2> </element1>
instead of:
<element1><element2>someData</element2></element1>
If this is not possible in woodstox, is there any other lightweight libs that can do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
有 com.sun.xml.txw2.output.IndentingXMLStreamWriter
There is com.sun.xml.txw2.output.IndentingXMLStreamWriter
通过 JDK:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
。Via the JDK:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
.如果您使用 StAX 游标 API,则可以通过将 XMLStreamWriter 包装在 缩进代理。 我在自己的项目中尝试过这一点,效果很好。
If you're using the StAX cursor API, you can indent the output by wrapping the XMLStreamWriter in an indenting proxy. I tried this in my own project and it worked nicely.
使用 JDK 转换器:
Using the JDK Transformer:
我建议下载 StAX 实用程序类 来自 java.net。 该包包含一个运行良好的 IndentingXMLStreamWriter 类。 (下载中包含源代码和 javadoc。)
Rather than relying on a com.sun...class that might go away (or get renamed com.oracle...class), I recommend downloading the StAX utility classes from java.net. This package contains a IndentingXMLStreamWriter class that works nicely. (Source and javadoc are included in the download.)
StaxMate 怎么样:
http://www.cowtowncoder.com/blog/archives/2006/09/entry_21.html
与 Woodstox 配合良好,快速,低功耗内存使用情况(没有构建内存树)和缩进,如下所示:
How about StaxMate:
http://www.cowtowncoder.com/blog/archives/2006/09/entry_21.html
Works well with Woodstox, fast, low-memory usage (no in-memory tree built), and indents like so:
如果您使用 XMLEventWriter,那么更简单的方法是:
if you are using XMLEventWriter, then an easier way to do that is:
不确定 stax,但最近这里有一个关于漂亮打印 xml 的讨论
漂亮打印xml from java
这是我尝试解决方案
如何 从 Java 漂亮打印 XML?
使用 org.dom4j.io.OutputFormat.createPrettyPrint() 方法
Not sure about stax, but there was a recent discussion about pretty printing xml here
pretty print xml from java
this was my attempt at a solution
How to pretty print XML from Java?
using the org.dom4j.io.OutputFormat.createPrettyPrint() method
如果您使用迭代方法 (XMLEventReader),那么在写入 XML 文件时,您不能仅将新行“\n”字符附加到相关 XMLEvent 吗?
If you're using the iterating method (XMLEventReader), can't you just attach a new line '\n' character to the relevant XMLEvents when writing to your XML file?
对于 Spring Batch,这需要一个子类,因为 JIRA BATCH-1867
但这需要额外的依赖项因为 Spring Batch 不包含缩进 StAX 输出的代码:
With Spring Batch this requires a subclass since this JIRA BATCH-1867
But this requires an additionnal dependency because Spring Batch does not include the code to indent the StAX output: