Monday, October 1, 2018

DOM  and SAX Parser for XML:
 The DOM Parser loads the complete XML content into a Tree structure. And we iterate through the Node and NodeList to get the content of the XML. 
DocumentBuilder builder = factory.newDocumentBuilder();
 
    //Load and Parse the XML document
    //document contains the complete XML as a Tree.
    Document document =
      builder.parse(
        ClassLoader.getSystemResourceAsStream("xml/employee.xml"));
 
 
    List empList = new ArrayList<>();
 
    //Iterating through the nodes and extracting the data.
    NodeList nodeList = document.getDocumentElement().getChildNodes();
 
    for (int i = 0; i < nodeList.getLength(); i++) {
 We will get the NodeList and parse.

SAX Parser for XML:
SAX Parser is different from the DOM Parser where SAX parser doesn’t load the complete XML into the memory, instead it parses the XML line by line triggering different events as and when it encounters different elements like: opening tag, closing tag, character data, comments and so on. This is the reason why SAX Parser is called an event based parser.

No comments: