| Author |
Appending data to existing XML file
|
Booma Devi
Ranch Hand
Joined: Nov 02, 2011
Posts: 61
|
|
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.. ?
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1776
|
|
Hi Rt,
The issue is that every a new DOM document gets created and written into the file. Check before you add whether the existing file (BN.xml) has already nodes or not.
Next time please UseCodeTags - I have added and updated the code below. See how good it looks.
|
 |
Booma Devi
Ranch Hand
Joined: Nov 02, 2011
Posts: 61
|
|
|
Thank you so much John for spending time to read my code and gave suggestion..
|
 |
Ashish Agre
Ranch Hand
Joined: Jan 22, 2011
Posts: 73
|
|
May be you are done with this, but i used this code to modify my XML File 
|
| B.E IT | SCJP 6.0 98 % |
|
 |
 |
|
|
subject: Appending data to existing XML file
|
|
|