Search code examples
javaxmlxml-parsingsaxdom4j

Parsing xml using Dom4j based on condition


I have the following XMLfile that i need to parse through and i need to select the firstname of the student whose person_type value=1. I am using dom4j in my java project and i am not able to find a solution to extract the firstname based on the value of the person_type. Any help would be appreciated.

<?xml version="1.0"?>
<class>
<student>
 <firstname>dinkar</firstname>
 <lastname>kad</lastname>
 <nickname>dinkar</nickname>
 <marks>85</marks>
 <person_types>
  <person_type>1</person_type>
  <person_description>POC</person_description>
 </person_types>
</student>
<student>
 <firstname>Vaneet</firstname>
 <lastname>Gupta</lastname>
 <nickname>vinni</nickname>
 <marks>95</marks>
 <person_types>
  <person_type>1</person_type>
  <person_description>Assistant</person_description>
 </person_types>
</student>
<student>
 <firstname>jasvir</firstname>
 <lastname>singn</lastname>
 <nickname>jazz</nickname>
 <marks>90</marks>
 <person_types>
  <person_type>1</person_type>`
  <person_description>Leader</person_description>
 </person_types>
</student>
</class>

Solution

  •  public static void main(String[] args) {
            try {
               File inputFile = new File("input.txt");
               SAXReader reader = new SAXReader();
               Document document = reader.read( inputFile );
    
               System.out.println("Root element :" 
                  + document.getRootElement().getName());
    
               Element classElement = document.getRootElement();
    
               List<Node> nodes = document.selectNodes("/class/student" );
               System.out.println("----------------------------");
               for (Node node : nodes) {
                 if("1".equals(node.selectSingleNode("person_types").selectSingleNode("person_type").getText())){
                     System.out.println("\nCurrent Element :" 
                             + node.getName());
                          System.out.println("Student roll no : " 
                             + node.valueOf("@rollno") );
                          System.out.println("First Name : " + node.selectSingleNode("firstname").getText());
                          System.out.println("Last Name : " + node.selectSingleNode("lastname").getText());
                          System.out.println("First Name : " + node.selectSingleNode("nickname").getText());
                          System.out.println("Marks : " + node.selectSingleNode("marks").getText());
                 }
               }
            } catch (DocumentException e) {
               e.printStackTrace();
            }
         }