How to create an XMLStreamWriter object

Classes for creating an XMLStreamWriter objec:

  • javax.xml.stream.XMLOutputFactory
  • javax.xml.stream.XMLStreamWriter
  • javax.xml.stream.XMLStreamException

Common methods of the XMLOutputFactory class:

Method Description
newInstance() A static method that returns an XMLOutputFactory object.
createXMLStreamWriter(out) Returns an XMLStremWriter object for the specified Writer or OutputStream object. This method throws an XMLSreamException.

Example 1: Code that creates an XMLStreamWriter object that writes to file

//Create the XMLOutputFactory object
XMLOutputFactory outputFactory = new XMLOutputFactory.newInstance();
try
{
// create the XMLStreamWriter object
FileWriter fileWriter = new FileWriter("products.xml");
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter);
// Writer XML data here
}
catch (IOException e)
{
e.printStackTrace();
}
catch (XMLStreamExcepion e)
{
e.printStackTrace();
}

Code that creates an XMLStreaWriter object that writes to the console

XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out);

Descriptions:

  • To write XML to an output stream, such as the console, you can supply any stream that implements the abstract OutputStream class as the argument for the createXMLStreamWriter method.

More info can be found here: