
parser xml one page to another

1)file.xml:
<school> <student> <name>Angelina</name> <address>Delhi</address> </student> <student> <name>Martina</name> <address>Mumbai</address> </student> </school>
2)Student.java:
class Student
{
String name;
String address;
Student(String name,String address){
this.name=name;
this.address=address;
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
}
3)ParseXmlFile.java:
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class ParseXmlFile{
public static void main(String argv[]) {
ArrayList<Student> list=new ArrayList<Student>();
try{
File file = new File("c:\\file.xml");
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
document.getDocumentElement().normalize();
System.out.println("Root element "+ document.getDocumentElement().getNodeName());
NodeList node = document.getElementsByTagName("student");
System.out.println("Information of the students");
for(int i = 0; i < node.getLength(); i++) {
Node firstNode = node.item(i);
if(firstNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) firstNode;
NodeList firstNameElemntList = element.getElementsByTagName("name");
Element firstNameElement = (Element) firstNameElemntList.item(0);
NodeList firstName = firstNameElement.getChildNodes();
Node n1=firstName.item(0);
String name=n1.getNodeValue();
NodeList lastNameElementList = element.getElementsByTagName("address");
Element lastNameElement = (Element)lastNameElementList.item(0);
NodeList lastName = lastNameElement.getChildNodes();
Node n2=lastName.item(0);
String address=n2.getNodeValue();
list.add(new Student(name,address));
}
}
for(Student st:list){
System.out.println(st.getName()+"\t"+st.getAddress());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.