Save below xml into emp.xml file.
<emps>
<emp id="1016">
<name>Nataraj</name>
<dep>Accounts</dep>
</emp>
<emp id="1015">
<name>Nagesh</name>
<dep>Marketing</dep>
</emp>
</emps>
Java code to read xml file:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class ParseXml {
public static void main(String a[]){
Document xmlDoc = null;
SAXBuilder builder = new SAXBuilder();
InputStream is = null;
Element root = null;
try {
is = new FileInputStream(new File("C:\\emp.xml"));
xmlDoc = builder.build(is);
if(xmlDoc != null){
root = xmlDoc.getRootElement();
System.out.println("Root element name: "+root.getName());
List
System.out.println("Emp Size: "+empList.size());
for(Element emp:empList){
System.out.println("Id: "+emp.getAttributeValue("id"));
Element name = emp.getChild("name");
System.out.println("Name: "+name.getText());
Element dep = emp.getChild("dep");
System.out.println("Deportment: "+dep.getText());
System.out.println("<--------------------------------------->");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
OUTPUT:
-----------
Root element name: emps
Emp Size: 2
Id: 1016
Name: Nataraj
Deportment: Accounts
<--------------------------------------->
Id: 1015
Name: Nagesh
Deportment: Marketing
<--------------------------------------->
No comments:
Post a Comment