4

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

4

3 回答 3

9

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

XMLStreamWriter writer =
  XMLOutputFactory.newInstance().createXMLStreamWriter(...);
writer = new IndentingXMLStreamWriter(writer);
...
于 2010-06-01T20:06:49.247 回答
4

在这里回答:Java 中的 StAX XML 格式

编辑:使用 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());

这给了你:

<?xml version="1.0" encoding="UTF-8"?>
<a>
  <b></b>
</a>
于 2010-06-01T11:12:09.033 回答
1

通过 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();
}
于 2012-07-17T06:57:21.987 回答