XMLStreamWriter in Java StAX
Streaming API for XML added in Java 6 provides a handy interface XMLStreamWriter which is used for writing XML documents. this API does not require building any specific object structure like in DOM and doing any intermediate tasks. It also supports namespaces by default which is very useful in more advanced situations.
Methods that are incorporated in order to create XMLStreamWriter object and write data into it are listed below as follows:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
There are certain limitations been attached with XMLStreamWriter in java StAX of which primarily are as follows:
- It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.
- XMLStreamWriter does not indent its output so it may be a bit hard to read using a plain text editor. Therefore, for reading, it is suggested to open it in a web browser most of which has a user-friendly interface to view the structure of XML documents.
- Create instance of XMLStreamWriter using XMLOutputFactory
- Write the header of the XML and proceed to write elements.
- After adding elements we can add attributes, character data, or CDATA
- Close opened elements
- Emptying elements or write comments
- Close and finish XML document
Now let us do discuss more how they are written later on implementing the same in our java program.
Step 1: Create instance of XMLStreamWriter using XMLOutputFactory.
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream);
Step 2: Write the header of the XML and proceed to write elements.
Step 3: After adding elements we can add attributes, character data, or CDATA.
xmlStreamWriter.writeAttribute("id", "10"); xmlStreamWriter.writeCharacters("hello world!"); xmlStreamWriter.writeCData("more text data");
Step 4: Closing opened elements
Step 5: Emptying elements or write comments, but do note it is an optional step
xmlStreamWriter.writeEmptyElement("used & new"); xmlStreamWriter.writeComment("Thank you!");
Step 6: Close and finish XML document.
<gfg id="10">hello world! <![CDATA[more text data]]> </gfg> <used & new/> <!--Thank you!-->
Streaming API for XML provides a very convenient, fast, and memory-efficient way to write XML documents without worrying about details and escaping special characters. It is a great alternative to DOM especially when you don’t need to keep and manage DOM tree in memory for any reason.