Java 中的 StAX XML 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/290326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:37:57  来源:igfitidea点击:

StAX XML formatting in Java

javaxmlformattingstaxwoodstox

提问by Lehane

Is it possible using StAX (specifically woodstox) to format the output xml with newlines and tabs, i.e. in the form:

是否可以使用StAX(特别是woodstox)使用换行符和制表符格式化输出xml,即格式:

<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?

如果这在 woodstox 中是不可能的,是否还有其他轻量级的库可以做到这一点?

采纳答案by Josh

Via the JDK: transformer.setOutputProperty(OutputKeys.INDENT, "yes");.

通过 JDK:transformer.setOutputProperty(OutputKeys.INDENT, "yes");.

回答by Spencer Kormos

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?

如果您正在使用迭代方法 (XMLEventReader),在写入 XML 文件时,您不能在相关的 XMLEvents 上附加一个新行 '\n' 字符吗?

回答by mlo55

Not sure about stax, but there was a recent discussion about pretty printing xml here

不确定 stax,但最近有一个关于漂亮打印 xml 的讨论here

pretty print xml from java

来自java的漂亮打印xml

this was my attempt at a solution

这是我的解决方案尝试

How to pretty print XML from Java?

如何从 Java 漂亮地打印 XML?

using the org.dom4j.io.OutputFormat.createPrettyPrint()method

使用org.dom4j.io.OutputFormat.createPrettyPrint()方法

回答by StaxMan

How about StaxMate:

StaxMate怎么

http://www.cowtowncoder.com/blog/archives/2006/09/entry_21.html

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:

适用于 Woodstox、快速、低内存使用(未构建内存树)以及如下缩进:



SMOutputFactory sf = new SMOutputFactory(XMLOutputFactory.newInstance());
SMOutputDocument doc = sf.createOutputDocument(new FileOutputStream("output.xml"));
doc.setIndentation("\n ", 1, 2); // for unix linefeed, 2 spaces per level    
// write doc like:    
SMOutputElement root = doc.addElement("element1");    
root.addElement("element2").addCharacters("someData");    
doc.closeRoot(); // important, flushes, closes output


回答by Andrew Swan

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.

如果您使用 StAX 游标 API,则可以通过将 XMLStreamWriter 包装在缩进代理中来缩进输出。我在自己的项目中尝试过这个,效果很好。

回答by Juha Syrj?l?

There is com.sun.xml.txw2.output.IndentingXMLStreamWriter

有 com.sun.xml.txw2.output.IndentingXMLStreamWriter

XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));

回答by Thad

Rather than relying on a com.sun...class that might go away (or get renamed com.oracle...class), I recommend downloading the StAX utility classesfrom java.net. This package contains a IndentingXMLStreamWriter class that works nicely. (Source and javadoc are included in the download.)

与其依赖可能会消失的 com.sun...class(或重命名为 com.oracle...class),我建议从 java.net下载StAX 实用程序类。这个包包含一个运行良好的 IndentingXMLStreamWriter 类。(源代码和 javadoc 包含在下载中。)

回答by Sebastien Lorber

With Spring Batch this requires a subclass since this JIRA BATCH-1867

使用 Spring Batch 这需要一个子类,因为这个JIRA BATCH-1867

public class IndentingStaxEventItemWriter<T> extends StaxEventItemWriter<T> {

  @Setter
  @Getter
  private boolean indenting = true;

  @Override
  protected XMLEventWriter createXmlEventWriter( XMLOutputFactory outputFactory, Writer writer) throws XMLStreamException {
    if ( isIndenting() ) {
      return new IndentingXMLEventWriter( super.createXmlEventWriter( outputFactory, writer ) );
    }
    else {
      return super.createXmlEventWriter( outputFactory, writer );
    }
  }

}

But this requires an additionnal dependency because Spring Batch does not include the code to indent the StAX output:

但这需要额外的依赖,因为 Spring Batch 不包含缩进 StAX 输出的代码:

<dependency>
  <groupId>net.java.dev.stax-utils</groupId>
  <artifactId>stax-utils</artifactId>
  <version>20070216</version>
</dependency>

回答by Roland

Using the JDK Transformer:

使用 JDK转换器

public String transform(String xml) throws XMLStreamException, TransformerException
{
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    Writer out = new StringWriter();
    t.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));
    return out.toString();
}

回答by Nh Wh

if you are using XMLEventWriter, then an easier way to do that is:

如果您使用的是 XMLEventWriter,那么更简单的方法是:

XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter writer = outputFactory.createXMLEventWriter(w);
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        Characters newLine = eventFactory.createCharacters("\n"); 
        writer.add(startRoot);
        writer.add(newLine);