0

So my code is simple and it creates what I want it to create, but I don't know if I'm really seeing any benefit to using the javax.xml.stream package for this.

Are my requirements simply too basic to really utilize the class? The only real benefits I see are that the writer.EndElement() and writer.EndDocument() properly close the tags, however I am not aware of a way to create new lines or tabs (aka proper formatting) without manually writing them as I've done below.

    public void WriteUserInfo(String username, String password) 
            throws FileNotFoundException, XMLStreamException {

        outputStream = new FileOutputStream(getXmlFile());
        factory = XMLOutputFactory.newInstance();
        writer = factory.createXMLStreamWriter(outputStream);
        writer.writeStartDocument(XMLTAG);
        writer.writeCharacters("\n");
        writer.writeStartElement(USER);
        writer.writeCharacters("\n\t");
        writer.writeStartElement(USERNAME);
        writer.writeCharacters(username);
        writer.writeEndElement();
        writer.writeCharacters("\n\t");
        writer.writeStartElement(PASSWORD);
        writer.writeCharacters(password);
        writer.writeEndElement();
        writer.writeCharacters("\n");
        writer.writeEndDocument();
        writer.close();
    }
Jens Bodal
  • 1,707
  • 1
  • 22
  • 32
  • 2
    (1) You'll get well-formed XML, even if you have ampersands or other illegal characters in your content. (2) There's no such thing as "proper formatting" of an XML document; line breaks between elements are simply a convention for human readability, and require any reader that doesn't care about them to explicitly ignore them. – kdgregory Mar 25 '14 at 18:04

1 Answers1

0

Consider using Saxon's implementation of the XMLStreamWriter interface. This provides a wide range of serialization options, including automatic indentation (plus all the other options available in XSLT xsl:output). You can get this via the s9api Serializer class.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164