How to 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 chched 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.writeStartDocuement("1.0");
writer.writeComment("Product data");
writer.writeStartElement("Products");
for (Product p : products)
{
writer.writeStartElement("Product");
writer.writeAttribute("Code", plgetCode());
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();
writer.flush();
writer.close();

Character Escape Description
< < less than
> > greater than
& & ampersand

Descriptions:

  • Since these methods thorw an XMLStreamException, you must handle the exceptions.

More info can be found here: