StAX XML formatting in Java

前端 未结 10 1402
-上瘾入骨i
-上瘾入骨i 2020-11-29 08:06

Is it possible using StAX (specifically woodstox) to format the output xml with newlines and tabs, i.e. in the form:


  
   someData
  &         


        
相关标签:
10条回答
  • 2020-11-29 08:59

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

    XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));
    
    0 讨论(0)
  • 2020-11-29 09:00

    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

    0 讨论(0)
  • 2020-11-29 09:04

    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?

    0 讨论(0)
  • 2020-11-29 09:06

    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();
    }
    
    0 讨论(0)
提交回复
热议问题