![]() |
Java StAX API was introduced in Java 6 and considered superior to DOM and SAX parsers. We can use Java StAX parser to read XML file and java Streaming API for XML (Java StAX) provides implementation for processing XML in java. The XMLEventWriter class in the Java StAX API allows you to write StAX XMLEvent’s either to a Writer, an OutputStream, or a Result (special JAXP object). Methods provides by XMLEventWriter to write data into it:
There are certain limitations been attached with XMLEventWriter in java StAX of which primarily are as follows:
Procedure:
They are as illustrated below as follows: Step 1 : Create instance of XMLEventWriter using XMLOutputFactory. XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEventWriter writer =factory.createXMLEventWriter( new FileWriter("F:\\gfg-XmlFile.xml")); Step 2: Write the header of the XML and proceed to create start elements. XMLEvent event = eventFactory.createStartDocument(); event = eventFactory.createStartElement("GFG", "/tag", "document"); Step 3: After adding elements we can add attributes, namespace. event = eventFactory.createNamespace("GeeksforGeeks-practice", "https://practice.horje.org"); writer.add(event); event = eventFactory.createAttribute("attribute", "value"); writer.add(event); Step 4: Flush and close opened elements. writer.flush(); writer.close(); Step 5: Add try and catch block. try { ----------code------------ } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Example Java
Output:
<?xml version='1.0' encoding='UTF-8'?> <GFG:document xmlns:GeeksforGeeks-practice="https://practice.horje.org" attribute="GFG> </GFG:document>
|
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |