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 |
---|---|---|
< | < | less than |
> | > | greater than |
& | & | ampersand |