XML File looses its format after reading and writing in Java



I'm writing a program in Java that it's going to read a XML file and do some modification,and then write the file with the same format.


The following is the code block that reads and writes the XML file:



final Document fileDocument = parseFileAsDocument(file);

final OutputFormat format = new OutputFormat(fileDocument);

try {
final FileWriter out = new FileWriter(file);
final XMLSerializer serializer = new XMLSerializer(out,format);
serializer.serialize(fileDocument);
}
catch (final IOException e) {
System.out.println(e.getMessage()).
}


This is the method used to parse the file:



private Document parseFileAsDocument(final File file) {
Document inputDocument = null;
try {
inputDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
}//catching some exceptions{}

return inputDocument;
}


I'm noticing two changes after the file is written: Before I had a node similar to this:



<instance ref='filter'>
<value></value>
</instance>


After reading and writing, the node looks like this:



<instance ref="filter">
<value/>


As you can see from above, the 'filter' has been changed to "filter" with double quote. The second change is <value></value> has been changed to <value/>. This change happens across the XML file whenever we have a node similar to <tag></tag> with no value in between. So if we have something like <tag>somevalue</tag>, there is no issue. Any thought please how to get the XML nodes format to be the same after writing? I'd appreciate it!


No comments:

Post a Comment