/ Published in: Java
Code is to demonstrate the use of DocumentBuilder to parse the XML file. And retrieve the data from it.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DocumentBuilderDemo { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder db = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); NodeList nodeList = root.getElementsByTagName("to"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i).getFirstChild(); } nodeList = root.getElementsByTagName("from"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i).getFirstChild(); } nodeList = root.getElementsByTagName("body"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i).getFirstChild(); } } } /* The simple.xml file that we used for parsing in above example. <?xml version="1.0"?> <msg> <note> <to>Tom</to> <from>Prince</from> <heading>Reminder</heading> <body>Hello how are u?</body> </note> <note> <to>Sania</to> <from>Prince</from> <heading>Joking</heading> <body>Welcome!!!</body> </note> </msg> */