Java 中的 StAX XML 格式化

发布于 2024-07-08 05:39:15 字数 299 浏览 11 评论 0原文

是否可以使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

樱&纷飞 2024-07-15 05:39:15

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

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

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

XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));
铜锣湾横着走 2024-07-15 05:39:15

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

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

丿*梦醉红颜 2024-07-15 05:39:15

如果您使用 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.

梦与时光遇 2024-07-15 05:39:15

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

Using the 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();
}
冰雪之触 2024-07-15 05:39:15

我建议下载 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.)

愁杀 2024-07-15 05:39:15

StaxMate 怎么样:

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

与 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

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:


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

夏夜暖风 2024-07-15 05:39:15

如果您使用 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);

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

XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter writer = outputFactory.createXMLEventWriter(w);
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        Characters newLine = eventFactory.createCharacters("\n"); 
        writer.add(startRoot);
        writer.add(newLine);
风月客 2024-07-15 05:39:15

不确定 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

等你爱我 2024-07-15 05:39:15

如果您使用迭代方法 (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?

━╋う一瞬間旳綻放 2024-07-15 05:39:15

对于 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 );
    }
  }

}

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

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

With Spring Batch this requires a subclass since this 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:

<dependency>
  <groupId>net.java.dev.stax-utils</groupId>
  <artifactId>stax-utils</artifactId>
  <version>20070216</version>
</dependency>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文