2 Replies Latest reply: Jul 11, 2011 6:03 AM by 874571 RSS

    Problem while parsing XML

    874571
      Hi All,
      I am parsing a xml file.Suppose it has student data of three classes and I want to parse it class-wise.

      I want the result as:
      class1- 3 students
      class2- 2 students
      class3- 4 students

      I tried following java code:

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = factory.newDocumentBuilder();
      Document doc = docBuilder.parse(file);
      NodeList nl = doc.getElementsByTagName("student");
      int totalStudents = nl.getLength();

      Its giving me the o/p as 9 students.

      Is there any way to parse the xml as I shown above.

      Thanks in advance.

      Below is my xml file


      *<data>*
      *<class1>*
      *<student>*
      *<name>aa</name>*
      *</student>*
      *<student>*
      *<name>bb</name>*
      *</student>*
      *<student>*
      *<name>cc</name>*
      *</student>*
      *</class1>*

      *<class2>*
      *<student>*
      *<name>xx</name>*
      *</student>*
      *<student>*
      *<name>yy</name>*
      *</student>*
      *</class2>*

      *<class3>*
      *<student>*
      *<name>pp</name>*
      *</student>*
      *<student>*
      *<name>qq</name>*
      *</student>*
      *<student>*
      *<name>rr</name>*
      *</student>*
      *<student>*
      *<name>ss</name>*
      *</student>*
      *</class3>*

      *</data>*
        • 1. Re: Problem while parsing XML
          gimbal2
          The parser will create a DOM tree of the entire document. After that it is up to you to extract the information you need from that tree structure.

          I see you want to split on the classes in the document, so loop through all the children of the root node (which according to your XML layout are always class nodes) and process the children of each class node you find, storing the information in beans.
          • 2. Re: Problem while parsing XML
            874571
            Can you please tell me in detail about this.

            Thanks in advance.