Hi,
Can any one tell how to append the new element to existing xml file? I have the following code..
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.*;
import javax.xml.transform.dom.DOMSource;
class processXML
{
public void process(
String name) throws Exception, DOMException,ParserConfigurationException
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db =dbf.newDocumentBuilder();
// Read books.xml file
Document dct=db.parse("C:\\Data\\books.xml");
Element child1 = dct.createElement("Name");
// Get the root node so we can explore its children
Element root = dct.getDocumentElement();
root.appendChild(child1);
// Get the element from the user..
Text text1 = dct.createTextNode(name);
// Append the element to existing XML file
root.getLastChild().appendChild(text1);
// Create blank document
Document mainDoc = db.newDocument();
Element root1 = mainDoc.createElement("Root1");
mainDoc.appendChild(root1);
// Copy the existing XML file with newly created element
root1.appendChild(mainDoc.importNode(root, true));
// Save the created DOM tree to XML file...
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new FileWriter("C:\\Data\\LBN.xml"));
DOMSource source = new DOMSource(mainDoc);
transformer.transform(source, result);
System.out.println("File saved!");
}
}
public class XMLTest
{
public static void main(String args[])throws Exception,DOMException
{
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter element");
String name = null;
processXML p=new processXML();
while((name=in.readLine())!=null)
{
p.process(name);
}
}
}
books.xml:
***********
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
- <Root>
<Name>rev</Name>
</Root>
When I add the element "Hello" to the books.xml file for the first time, system appended the element Hello in books.xml file.. but for the second time , it overwrite the hello .. How can i append the element to existing file.. ?