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();
}
}
}