【问题标题】:Formatting XML file using StAX使用 StAX 格式化 XML 文件
【发布时间】:2011-02-26 07:29:03
【问题描述】:

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

【问题讨论】:

标签: java xml stax


【解决方案1】:

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

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

【讨论】:

  • 你能命名jar文件吗?我没有在给定站点获得下载选项。
  • @Chris 我用春季批次试过这个。我得到了正确格式的 xml,但是当我将它部署到 weblogic 并运行批处理作业时,我看到“ ”插入到每行的末尾。如何避免这种情况?
  • @Maverick:不确定...你可能想试试StAXON,它有一个类似的类(de.odysseus.staxon.xml.util.PrettyXMLStreamWriter )。
【解决方案2】:

在这里回答:StAX XML formatting in Java

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

【讨论】:

  • 我确实检查过了,你能举一些例子,让代码 sn-p 传递我的 xml 文件并设置缩进选项。在上述位置提供的示例中,我无法理解如何设置所有这些参数。
  • 我在帖子中添加了一个示例。
  • 谢谢,这真的很有帮助
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2011-08-24
    相关资源
    最近更新 更多