Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

is there really no way to directly write formatted XML using javax.xml.stream.XMLStreamWriter (Java SE 6)??? This is really unbelievable, as other XML APIs such as JAXB and some DOM libraries are able to do this. Even the .NET XMLStreamWriter equivalent is able to this AFAIK (if I remember correctly the class is System.Xml.XmlTextWriter).

This means the only option I have is to reparse the XML to generate formatted output??

E.g.:

            StringWriter sw = new StringWriter();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
    XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(sw);
    writeXml(xmlStreamWriter);
    xmlStreamWriter.flush();
    xmlStreamWriter.close();

    TransformerFactory factory = TransformerFactory.newInstance();

    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter formattedStringWriter = new StringWriter();
    transformer.transform(new StreamSource(new StringReader(sw.toString())), new StreamResult(formattedStringWriter));
    System.out.println(formattedStringWriter);

The problem with this solution is the property "{http://xml.apache.org/xslt}indent-amount". I didn't find any documentation about it and it doesn't seem to be guaranteed to be portable.

So what other options do I have, if I want to do this with standard Java 6 classes? Create a JAXB or DOM object graph just for pretty printing??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

This exact question has been answered some months ago and one of the answers is to use the IndentingXMLStreamWriter class:

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

It is a neat solution as far as the code goes, but careful: this is a com.sun.* class, there is no guarantee of its general availability...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...