4

can any one share good document for dom parser in java.

thanks

Ashish
  • 1,527
  • 4
  • 17
  • 33
  • 2
    I'll upvote back as soon as you accept an answer. Thanks. – Anton Kraievyi Apr 10 '11 at 18:30
  • You may write one by yourself. See this http://stackoverflow.com/a/8346867/851432 – Jomoos Dec 01 '11 at 19:13
  • You might want to consider OXM instead of traditional DOM parsing too? Java allows you to convert between Java Objects and XML definitions of java objects using technologies like Jackson etc. – Richard Feb 16 '15 at 17:14

2 Answers2

5

Following are tutorial for using DOM in java:

  1. xml dom
  2. DOM-Parser
  3. java-xml-dom
  4. dom example

Hope this helps.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
1

Check this Simple Parser XML with DOM Example and this Sax Example:

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

    File fXmlFile = new File("/Users/mkyong/staff.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("staff");

    System.out.println("----------------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            System.out.println("Staff id : " + eElement.getAttribute("id"));
            System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
            System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
            System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
            System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

        }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
  }

}
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130