How to write XML file in Java (DOM Parser) With Examples

Earlier we learned how to read XML file and how to edit XML file in java using DOM Parser, today we will learn how to write an XML file in java using DOM Parser.

Here is the requirement for our XML file.

  1. The root element will be “Employees” with namespace “”. This root element will contain the list of Employees.
  2. The employee information will be written in “Employee” element. There will be two employees information in the XML file.
  3. Every employee has an attribute named “id”
  4. Employee element will have four elements – “name”, “age”, “role”, “gender”.

Here is the java program for above requirement.

Notice that I have created two StreamResult, one to print XML in console for debugging purpose and another to write it to file.

Here is the output XML from above program.

The XML is not formatted, if you want XML to be properly formatted, read format XML in java.

By admin

Leave a Reply

%d bloggers like this: