DOM Parser demo using DocumentBuilder.


/ Published in: Java
Save to your folder(s)

Code is to demonstrate the use of DocumentBuilder to parse the XML file. And retrieve the data from it.


Copy this code and paste it in your HTML
  1. import java.io.File;
  2. import java.io.IOException;
  3.  
  4. import javax.xml.parsers.DocumentBuilder;
  5. import javax.xml.parsers.DocumentBuilderFactory;
  6. import javax.xml.parsers.ParserConfigurationException;
  7.  
  8. import org.w3c.dom.Document;
  9. import org.w3c.dom.Element;
  10. import org.w3c.dom.Node;
  11. import org.w3c.dom.NodeList;
  12. import org.xml.sax.SAXException;
  13.  
  14.  
  15. public class DocumentBuilderDemo {
  16.  
  17.  
  18. public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
  19. DocumentBuilder db = null;
  20. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  21. db = dbf.newDocumentBuilder();
  22. Document doc = db.parse(new File("c:\\simple.xml"));
  23.  
  24. Element root = doc.getDocumentElement();
  25. System.out.println(root.getNodeName());
  26.  
  27. System.out.println("========================================================================");
  28.  
  29. NodeList nodeList = root.getElementsByTagName("to");
  30.  
  31. for (int i = 0; i < nodeList.getLength(); i++) {
  32. Node node = nodeList.item(i).getFirstChild();
  33. System.out.println(node.getNodeValue());
  34. }
  35.  
  36. System.out.println("========================================================================");
  37.  
  38. nodeList = root.getElementsByTagName("from");
  39.  
  40. for (int i = 0; i < nodeList.getLength(); i++) {
  41. Node node = nodeList.item(i).getFirstChild();
  42. System.out.println(node.getNodeValue());
  43. }
  44.  
  45. System.out.println("========================================================================");
  46.  
  47. nodeList = root.getElementsByTagName("body");
  48.  
  49. for (int i = 0; i < nodeList.getLength(); i++) {
  50. Node node = nodeList.item(i).getFirstChild();
  51. System.out.println(node.getNodeValue());
  52. }
  53.  
  54. System.out.println("========================================================================");
  55.  
  56.  
  57. }
  58.  
  59. }
  60.  
  61.  
  62. /*
  63. The simple.xml file that we used for parsing in above example.
  64.  
  65.  
  66. <?xml version="1.0"?>
  67. <msg>
  68. <note>
  69. <to>Tom</to>
  70. <from>Prince</from>
  71. <heading>Reminder</heading>
  72. <body>Hello how are u?</body>
  73. </note>
  74. <note>
  75. <to>Sania</to>
  76. <from>Prince</from>
  77. <heading>Joking</heading>
  78. <body>Welcome!!!</body>
  79. </note>
  80. </msg>
  81.  
  82. */

URL: DocumentBuilderDemo.java

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.