简体   繁体   English

Java中的StAX XML格式

[英]StAX XML formatting in Java

Is it possible using StAX (specifically woodstox) to format the output xml with newlines and tabs, ie 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中无法做到这一点,是否有其他轻量级库可以做到这一点?

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));

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

If you're using the StAX cursor API, you can indent the output by wrapping the XMLStreamWriter in an indenting proxy . 如果您正在使用StAX游标API,则可以通过将XMLStreamWriter包装在缩进代理中来缩进输出。 I tried this in my own project and it worked nicely. 我在自己的项目中试过这个并且效果很好。

Using the JDK Transformer : 使用JDK Transformer

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();
}

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. 我建议从java.net下载StAX实用程序类 ,而不是依赖于可能会消失的com.sun ...类(或者重命名为com.oracle ...类)。 This package contains a IndentingXMLStreamWriter class that works nicely. 这个包包含一个可以很好地工作的IndentingXMLStreamWriter类。 (Source and javadoc are included in the download.) (源代码和javadoc包含在下载中。)

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

如果您正在使用迭代方法(XMLEventReader),那么在写入XML文件时,是否只能将新行'\\ n'字符附加到相关的XMLEvents?

Not sure about stax, but there was a recent discussion about pretty printing xml here 不确定stax,但最近有一个关于漂亮打印xml的讨论

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()方法

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>

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM