Showing posts with label DOM XML parsing. Show all posts
Showing posts with label DOM XML parsing. Show all posts

Monday, May 13, 2013

XML An Introduction

Wednesday, September 5, 2012

Create XML File in JAVA using DOM


package com.test;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXMLInJava {
public static void main(String argv[]) {
        CreateXMLInJava createXml = new CreateXMLInJava();
        createXml.createXML();
}
public void createXML() {
    try {
         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(“Company”);
       doc.appendChild(rootElement);
       // staff elements
       Element staff = doc.createElement(“Dept”);
       rootElement.appendChild(staff);
       // set attribute to staff element
       Attr attr = doc.createAttribute(“id”);
       attr.setValue(“1″);
       staff.setAttributeNode(attr);
       // can be written as
       // staff.setAttribute(“id”, “1″);
       // firstname elements
      Element firstname = doc.createElement(“Firstname”);
       firstname.appendChild(doc.createTextNode(“mallik”));
       staff.appendChild(firstname);
      // lastname elements
      Element lastname = doc.createElement(“Lastname”);
      lastname.appendChild(doc.createTextNode(“Gunda”));
      staff.appendChild(lastname);
        // salary elements
      Element salary = doc.createElement(“Salary”);
      salary.appendChild(doc.createTextNode(“100000″));
      staff.appendChild(salary);
      // write the content into xml file
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(new File(“D:\\test.xml”));
     // Output to console for testing
     // StreamResult result = new StreamResult(System.out);
       transformer.transform(source, result);
      System.out.println(“File saved!”);
   } catch (ParserConfigurationException pce) {
       pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();
  }
 }
}

Sunday, February 12, 2012

Difference between SAX and DOM


SAX  stands for Simple API for XML. It is a standard interface for event based XML parsing. Programmers provide handlers to deal with different events as the document is passed.

If we use SAX API to pass XML documents have full of control over what happens when the event occur as result, customizing the parsing process extensively. For example a programmer might decide to stop an XML document as as soon as the parser encounters an error that indicate that the document is invalid rather than waiting until the document is parsed. Thus improve the performance.

DOM stands for Document Object Model. DOM reads an xml document into memory and represents as it as tree. Each node of tree represents a particular piece of data from the original document. The main drawback is that the entire xml document has to be read into memory for DOM to create the tree which might decrease the performance of an application as the xml document get larger.

Sunday, November 13, 2011

XML Parsing Example using DOM in Java


package com.test;


import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XMLParsing {
  public static void main(String arg[]) throws Exception{

          String xmlRecords = "<data><employee><name>A</name>"
        + "<title>Manager</title></employee></data>";


    DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));


    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("employee");


    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);


      NodeList name = element.getElementsByTagName("name");
      Element line = (Element) name.item(0);
      System.out.println("Name: " + getCharacterDataFromElement(line));


      NodeList title = element.getElementsByTagName("title");
      line = (Element) title.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }
  }
  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterData) child;
      return cd.getData();
    }
    return "";
  }
}




Related Links:
                   XML Parsing using SAX Parser in Java
           Read Properties File in java
                   J2EE Design Patterns