Adding Attributes and Namespace Declarations to a Start Element Closing the Output Stream

4-18 Programming XML for Oracle WebLogic Server xmlw.writeStartElementname; xmlw.writeCharactersJane Doe; xmlw.writeEndElement; xmlw.writeCharacters\n;

4.3.5 Adding Attributes and Namespace Declarations to a Start Element

Use the writeAttribute method right after a start element event to add attributes to the element. You can specify a prefix for the attribute, as well as the URI it is bound to, or specify no prefix at all. For example, assume you want to create the following snippet of XML: person gender=f The Java code to produce this XML is as follows: xmlw.writeStartElementperson; xmlw.writeAttributegender,f; xmlw.writeCharacters\n; Use the writeNamespace method to write a namespace to the output stream. It is up to the programmer to ensure that the current event allows namespace writing, such as start element; if the current event does not allow namespace writing, a javax.xml.stream.XMLStreamException is thrown. Use appropriate flavors of other writeXXX methods to specify a prefix for an event and the URI to which it is bound. For example, the following XML output shows a namespace declaration for the person element, and the one prefix specified for the one child element: person xmlns:one=http:namespaceOne gender=f one:name hair=pigtails freckles=yesPippi Longstockingone:name person The Java code to produce this XML is as follows: Write the root element person with a single attribute gender xmlw.writeStartElementperson; xmlw.writeNamespaceone, http:namespaceOne; xmlw.writeAttributegender,f; xmlw.writeCharacters\n; Write the name element with some content and two attributes xmlw.writeCharacters ; xmlw.writeStartElementone, name, http:namespaceOne; xmlw.writeAttributehair,pigtails; xmlw.writeAttributefreckles,yes; xmlw.writeCharactersPippi Longstocking; End the name element xmlw.writeEndElement; xmlw.writeCharacters\n; End the person element xmlw.writeEndElement; Using the Streaming API for XML StAX 4-19

4.3.6 Closing the Output Stream

It is good programming practice to explicitly close the XMLStreamWriter when you are finished with it to free up resources. To close the writer, use the XMLStreamWriter.close method, as shown in the following example: Close the XMLStreamWriter to free up resources xmlw.close;

4.4 Properties Defined for the XMLInputFactory Interface