Java Reference
In-Depth Information
//create the writer
final XMLStreamWriter xsw =
factory.createXMLStreamWriter(fos);
xsw.setDefaultNamespace(NS);
//open the document. Can also add encoding, etc
xsw.writeStartDocument("1.0");
xsw.writeEndDocument();
xsw.writeComment("Powered by StAX");
//make enclosing book
xsw.writeStartElement("book");
xsw.writeNamespace("b", NS);
xsw.writeAttribute("sku", "345_iui");
//make title child element
xsw.writeStartElement(NS, "title");
xsw.writeCharacters("White Noise");
xsw.writeEndElement(); //close title
xsw.writeEndElement(); //close book
//clean up
xsw.flush();
fos.close();
xsw.close();
out.print("All done.");
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (XMLStreamException xse) {
xse.printStackTrace();
}
}
}
The API is very flexible, and allows you to write XML with varying degrees of well-formed-
ness and validity. You can quickly and cleanly produce XML snippets suitable for transfer into
the payload of a SOAP body or anywhere else you'd like to stick some markup.
Executing this program gives you the following result:
<?xml version="1.0"?>
<!--Powered by StAX-->
Search WWH ::




Custom Search