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:
- writeStartDocument()
- writeStartElement()
- writeCharacters()
- writeEndElement()
- writeEndDocument()
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.
Procedure:
- 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.
xmlStreamWriter.writeStartElement("gfg");
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
xmlStreamWriter.writeEndElement();
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.
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
Example
Java
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class StaxXMLStreamWriter {
public static void main(String[] args)
throws FileNotFoundException, XMLStreamException,
UnsupportedEncodingException
{
try {
String filePath = "D:\\gfg_file.xml" ;
Writer fileWriter = new FileWriter(filePath);
XMLOutputFactory xmlOutputFactory
= XMLOutputFactory.newInstance();
XMLStreamWriter xmlStreamWriter
= xmlOutputFactory.createXMLStreamWriter(
fileWriter);
xmlStreamWriter.writeStartElement( "gfg" );
xmlStreamWriter.writeAttribute( "id" , "10" );
xmlStreamWriter.writeCharacters( "hello world!" );
xmlStreamWriter.writeCData( "more text data" );
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEmptyElement( "used & new" );
xmlStreamWriter.writeComment( "Thank you!" );
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.flush();
xmlStreamWriter.close();
System.out.println(
"XML file created successfully." );
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output:
<gfg id="10">hello world!
<![CDATA[more text data]]>
</gfg>
<used & new/>
<!--Thank you!-->
Conclusion:
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
16 Sep, 2021
Like Article
Save Article