Java get XML File
In this section, you will study how the java application read the XML file. For this, you need to create a XML file.
Here is the employee.xml file:
<?xml version="1.0"?> <company> <employee> <firstname>Anusmita</firstname> <lastname>Singh</lastname> </employee> </company> |
Now to read the 'employee.xml' file, we have used DocumentBuilderFactory to enable application to obtain a parser that produces DOM object from XML documents. Then the DocumentBuilder obtains the DOM Document instances from an XML document. It can also parse and build the XML document. The Document class access the document's data.
builder.parse(file)- This method parse the content of 'employee.xml'
file as an XML document an return the DOM object.
getDocumentElement()- This method allows direct access to the child
node that is the root element.
getNodeName()- This method returns the node name.
doc.getElementsByTagName("employee")-This method returns the
list of nodes of all the Elements with a given tag name.
getChildNodes()-This method provides all the children of this node.
getNodeValue()- This method returns the node value.
Here is the code of GetXML.java
import org.w3c.dom.*; import java.io.File; import javax.xml.parsers.*; public class GetXML { public static void main(String argv[]) { try { File file = new File("employee.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); doc.getDocumentElement().normalize(); System.out.println("Root element " + doc.getDocumentElement().getNodeName()); NodeList list = doc.getElementsByTagName("employee"); for (int i = 0; i < list.getLength(); i++) { Node node1 = list.item(i); if (node1.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node1; NodeList firstNodeElementList = element.getElementsByTagName("firstname"); Element element1 = (Element) firstNodeElementList.item(0); NodeList firstNodeList = element1.getChildNodes(); System.out.println("First Name : " + ((Node) firstNodeList.item(0)).getNodeValue()); NodeList lastNodeElementList = element.getElementsByTagName("lastname"); Element element2 = (Element) lastNodeElementList.item(0); NodeList lastNodeList = element2.getChildNodes(); System.out.println("Last Name : " + ((Node) lastNodeList.item(0)).getNodeValue()); } } } catch (Exception e) {} } }
The content of XML file is displayed on the console: