The sample XML file:
<?xml version="1.0"?>
<company name="my comapany">
<employee id="1">
<name>Mike</name>
</employee>
<employee id="2">
<name>Mark</name>
</employee> </company>
Java code to read the XML file:
package pkg;
import java.io.File;import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;
public class XMLReader { public void readXML(String fileName) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse(new File(fileName)); //GET THE ROOT ELEMENT Element root = document.getDocumentElement(); System.out.println("Root: " + root.getNodeName()); System.out.println("Company Name: " + root.getAttribute("name")); //GET THE LIST OF CHILD ELEMENTS UNDER ROOT NodeList employeeList = root.getElementsByTagName("employee"); System.out.println("Total employees: " + employeeList.getLength()); Element employee; String name = null, id = null; for(int i=0;i<employeeList.getLength();i++) { employee = (Element)employeeList.item(i); //FETCH ID OF EMPLOYEE if(employee.hasAttributes()) { id = employee.getAttributes().getNamedItem("id").getNodeValue(); } //GET NAME OF THE EMPLOYEE name = employee.getElementsByTagName("name").item(0).getTextContent(); System.out.println("Id: " + id + "\tName: " + name); } }}Happy parsing !!! :)
No comments:
Post a Comment