Hi all,
I am writing a
java code to update xml file elements . I need to know how to write the changes to the xml file.I used the setNodevalue() method but the change isn't reflecting in the xml file.I am parsing the xml file using sax parser.I am comparing an arraylist containing the tags that need to be updated with the elements of the xml file .In case of a match i need to update the xml file elements with values in a 2nd arraylisy(the index of the tags and its value are same in both arraylist).The xml file is not updated because the setnodevalue() in my code is updating the arraylist instead i should write the changes to the xml file.
Kindly share your suggestions and help me.
For reference
The following is a rough code that i have written,if it works i can use the functionality as part of an application that i am developing
package com;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class
Test {
String s1[] = null;
static ArrayList<String> tagvalue = new ArrayList<String>();
static ArrayList<String> l = new ArrayList <String>();
NodeList fstNmElmntLst =null;
static Element fstElmnt =null;
public static void main(String args[]) {
// tag values that need to be compared
l.add("Company_A");
l.add("Company_B");
l.add("Company_C");
l.add("Company_D");
//arraylist containing values that need to be updated
tagvalue.add("NEW JERSEY CITY");
tagvalue.add("MUMBAI");
tagvalue.add("LONDON");
tagvalue.add("GENEVA");
try {
File file = new File("C:\\Documents and Settings\\ravi\\Desktop\\test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document
doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element "+ doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("HeadQuaters");
Node fstNode = nodeLst.item(0);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
for (int i = 0; i < l.size(); i++) {
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName((String) l.get(i));
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println(" current xml node value:"+ ((Node) fstNm.item(0)).getNodeValue());
// the following line is updating the node but not the required xml file element
((Node)fstNm.item(0)).setNodeValue((String)tagvalue.get(i));
fstNmElmnt.appendChild((Node)fstNm.item(0));
System.out.println(" updated xml node value:"+ ((Node) fstNm.item(0)).getNodeValue());
// need to proceed from here to update the xml
-
-
-
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks in advance
S.Rajagopal