Formatting XML file using StAX

梦想与她 提交于 2019-12-17 19:26:09

问题


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.


回答1:


stax-utils provides class IndentingXMLStreamWriter which does the job:

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



回答2:


Answered here: StAX XML formatting in Java

EDIT: A quick example (without resource cleaning) using 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>



回答3:


Example pretty printing OMElement (Axiom library) via StAX:

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


来源:https://stackoverflow.com/questions/2949203/formatting-xml-file-using-stax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!