CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

XML

XML
StAX
Create XMLStreamWriter object

Classes for creating an XMLStreamWriter object

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 XMLStreamWriter object for the specified Writer or OutputStream object. This method throws an XMLStreamException.

Code that creates an XMLStreamWriter object that writes to a file

// Create the XMLOutputFactory object
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();

try
{
    // Create the XMLStreamWriter object
    FileWriter fileWriter =
        new FileWriter("products.xml");
    XMLStreamWriter writer =
        outputFactory.createXMLStreamWriter(fileWriter);

    // Write XML data here
}
catch (IOException e)
{
    e.printStackTrace();
}
catch (XMLStreamException e)
{
    e.printStackTrace();

Code that creates an XMLStreamWriter object that writes to the console

XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out);
Previous | Create XMLStreamWriter object | Write XML | Create XMLStreamReader object | Read XML | Class that works with an XML file