Read XML File

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.w3c.dom.NodeList;
public class xmlReader{
public static void main(String args[]){
try{
String key=null;
String value=null;
String Temp=null;
File file=new File("C:/Testxml/DEL_IN.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());
Node rootnode = doc.getDocumentElement();
System.out.println(rootnode.getNodeName());

// Steps for Getting id
NodeList idList = doc.getElementsByTagName("id");
Element idElement = (Element)idList.item(0);
NodeList childNodes = idElement.getChildNodes();
System.out.println(((Node) childNodes.item(0)).getNodeValue());

// Steps for Getting ActionType
NodeList actionList = doc.getElementsByTagName("action");
Element actionElement = (Element)actionList.item(0);
NodeList childNodes1 = actionElement.getChildNodes();
System.out.println(((Node) childNodes1.item(0)).getNodeValue());

// Steps for Getting ServiceType
NodeList serviceList = doc.getElementsByTagName("servicetype");
Element serviceElement = (Element)serviceList.item(0);
NodeList childNodes2 = serviceElement.getChildNodes();
System.out.println(((Node) childNodes2.item(0)).getNodeValue());

NodeList nodeLst=doc.getElementsByTagName("param");
System.out.println("all the key value parameter");
for(int s=0;s
Node fstNode = nodeLst.item(s);
if(fstNode.getNodeType()==Node.ELEMENT_NODE){
Element fstElmnt=(Element)fstNode;
NodeList fstNmElmntLst=fstElmnt.getElementsByTagName("key");
Element fstNmElmnt= (Element)fstNmElmntLst.item(0);
NodeList fstNm= fstNmElmnt.getChildNodes();
System.out.println("key : " + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst =fstElmnt.getElementsByTagName("value");
Element lstNmElmnt=(Element)lstNmElmntLst.item(0);
NodeList lstNm= lstNmElmnt.getChildNodes();
System.out.println("value : " + ((Node) lstNm.item(0)).getNodeValue());

}

}
}catch (Exception e) {
e.printStackTrace();
}
}
}







Post a Comment

أحدث أقدم