tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > JXPath > Parse XML through Document Container

Parse XML through Document Container 

JXPath is a java library for Object Graph Navigation using the XPath syntax. This requires the libraries commons-jxpath-1.3.jar, commons-beanutils.jar and commons-logging.jar to be in classpath. The following example shows parsing and traversing XML in JXPath.

File Name  :  
/JXPATH001/config/student_class.xml 

File Name  :  
com/bethecoder/tutorials/jxpath/DocumentContainerTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.jxpath;

import java.net.URL;
import java.util.Iterator;

import org.apache.commons.jxpath.Container;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.xml.DocumentContainer;

public class DocumentContainerTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    //Get the URL the of XML document
    URL url = DocumentContainerTest.class.getClassLoader().getResource("student_class.xml");
    
    //Construct document container from the URL to XML
    Container container = new DocumentContainer(url);
    
    JXPathContext context = JXPathContext.newContext(container);
    
    Iterator<?> subjects = context.iterate("/studentClass/subjects_list/subject");
      while (subjects.hasNext()) {
        System.out.println(subjects.next());
      }
      
      Iterator<?> stdNames = context.iterate("/studentClass/student_list/student/firstName");
      while (stdNames.hasNext()) {
        System.out.println(stdNames.next());
      }
      
      System.out.println(context.getValue("/studentClass/student_list/student[@id='1']/firstName"));
  }

}
   

It gives the following output,
Maths
Physics
Chemistry

Sriram
Sudhakar

Sriram



 
  


  
bl  br