java 使用 StAX 格式化 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2949203/
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-10-29 23:37:27  来源:igfitidea点击:

Formatting XML file using StAX

javaxmlstax

提问by Anurag

I am using StAX XML stream writer to write the XML file. It writes all the data in a single line. I want all the tags to be indented instead of a single line.

我正在使用 StAX XML 流编写器来编写 XML 文件。它将所有数据写入一行。我希望所有标签都缩进而不是一行。

回答by chris

stax-utilsprovides class IndentingXMLStreamWriterwhich does the job:

stax-utils提供了IndentingXMLStreamWriter完成这项工作的类:

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

回答by k_b

Answered here: StAX XML formatting in Java

在此处回答:Java 中的 StAX XML 格式

EDIT: A quick example (without resource cleaning) using stax-utils (https://stax-utils.dev.java.net/):

编辑:使用 stax-utils ( https://stax-utils.dev.java.net/) 的一个快速示例(没有资源清理):

XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
FileOutputStream file = new FileOutputStream("d:/file.xml");
XMLEventWriter writer = xmlOutputFactory.createXMLEventWriter(file);
writer = new IndentingXMLEventWriter(writer);
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
writer.add(eventFactory.createStartDocument());
writer.add(eventFactory.createStartElement("", "", "a"));
writer.add(eventFactory.createStartElement("", "", "b"));
writer.add(eventFactory.createEndElement("", "", "b"));
writer.add(eventFactory.createEndElement("", "", "a"));
writer.add(eventFactory.createEndDocument());

This gives you:

这给你:

<?xml version="1.0" encoding="UTF-8"?>
<a>
  <b></b>
</a>

回答by Rudi Wijaya

Example pretty printing OMElement (Axiom library) via StAX:

通过 StAX 的漂亮打印 OMElement(Axiom 库)示例:

OMElement mapArg = fac.createOMElement(name, elementNs);
mapArg.addAttribute("type", soapXml.getPrefix() + ":Map", xsi);
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(value);
for (PropertyDescriptor property : properties) {
    if (property.getName().equals("class"))
        continue;
    try {
        mapArg.addChild(keyValue(property.getName(),
                PropertyUtils.getProperty(value, property.getName())));
    } catch (Exception e) {
    }
}
final StringWriter stringWriter = new StringWriter();
try {
    IndentingXMLStreamWriter xmlWriter = new IndentingXMLStreamWriter(StaxUtilsXMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter));
    mapArg.serialize(xmlWriter);
    System.out.println(stringWriter.toString());
} catch (XMLStreamException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}