There is a simple xml in the following format
<configuration>
<property>
<name>crawling.depth</name>
<value>1</value>
<description/>
</property>
<property>
<name>video.appid</name>
<value>2</value>
<description>Value modified @25-06-2014 11:37:28.731</description>
</property>
</configuration>
At start up of my application, I generate an id and set the same in the video.appid property of the XML.
I am using a simple DOM parser and the XML gets updated properly, but during repeated start up process, noticed that the space between the two properties is getting added. after five or so modifications, the file looks like the one below.
<configuration>
<property>
<name>crawling.depth</name>
<value>1</value>
<description/>
</property>
<property>
<name>video.appid</name>
<value>2</value>
<description>Value modified @25-06-2014 12:30:18.125</description>
</property>
</configuration>
I remove the property and re-add the same into the XML, that I guess is the problem. while writing it back is there any way to reformat the whole file? so that the empty lines could be avoided.
tried googling it and got only indenting related info, which is not the problem here.
Thanks in advance.
Edit: Code which does the update:
public static boolean updatePropInFile(File file, Map propMap){
boolean success = false;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
NodeList props = doc.getElementsByTagName("property");//No I18N
List<Element> elements = new ArrayList<Element>();
for(int i=0;i<props.getLength();i++){
Element prop = (Element)props.item(i);
Element nme = (Element)prop.getElementsByTagName("name").item(0);//No I18N
String propName = nme.getTextContent();
Iterator it = propMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().equals(propName)){
prop.getParentNode().removeChild(prop);
i--;
}
}
}
Iterator it = propMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
elements.add(createPropertyElement(doc,String.valueOf(pairs.getKey()),String.valueOf(pairs.getValue())));
}
Node root = doc.getElementsByTagName("configuration").item(0);//No I18N
for(Element ele:elements){
root.appendChild(ele);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");//No I18N
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");//No I18N
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
success=true;
} catch (Exception pce) {
success=false;
}
return success;
}