CIS 35A: Introduction to Java Programming

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

XML

XML
StAX
Write XML

Common methods of the XMLStreamWriter object

Method Description
writeStartDocument(version) Writes the XML declaration.
writeStartElement(name) Writes the start tag for an element.
writeAttribute(name, value) Writes an attribute for the current element.
writeCharacters(value) Writes characters.
writeComment(value) Writes an XML comment.
writeDTD(value) Writes a DTD section.
writeEndElement() Writes the end tag for the current element.
flush() Writes any cached data to the underlying output mechanism.
close() Closes the XMLStreamWriter object and frees any resources associated with it.

Code that writes an XML document to a stream

writer.writeStartDocument("1.0");
writer.writeComment("Product data");
writer.writeStartElement("Products");
for (Product p : products)
{
    writer.writeStartElement("Product");
    writer.writeAttribute("Code", p.getCode());

    writer.writeStartElement("Description");
    writer.writeCharacters(p.getDescription());
    writer.writeEndElement();

    writer.writeStartElement("Price");
    double price = p.getPrice();
    writer.writeCharacters(Double.toString(price));
    writer.writeEndElement();

    writer.writeEndElement(); // for the Product element
}
writer.writeEndElement();     // for the Products element
writer.flush();
writer.close();

Escape characters that the writeCharacters method automatically uses

Character Escape Description
< &lt; less than
> &gt; greater than
&&amp; ampersand
Previous | Create XMLStreamWriter object | Write XML | Create XMLStreamReader object | Read XML | Class that works with an XML file