tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 XML > XOM > Xpath Query Positional Elements

Xpath Query Positional Elements 

XOM (XML Object Model) is a tree based java API for processing XML by taking the best ideas from SAX and DOM. It is simple, fast and easy to use. This requires the library xom-1.2.7.jar to be in classpath. The following example shows querying an XML document using XPath expression.

File Name  :  
/XOM001/config/randoms.xml 

File Name  :  
com/bethecoder/tutorials/xom/tests/XpathQuery7.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.xom.tests;

import java.io.IOException;
import java.io.InputStream;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Nodes;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

public class XpathQuery7 {

  /**
   @param args
   @throws IOException 
   @throws ParsingException 
   @throws ValidityException 
   */
  public static void main(String[] argsthrows ValidityException, ParsingException, IOException {
    Builder builder = new Builder();
    InputStream ins = XpathQuery7.class.getClassLoader()
          .getResourceAsStream("randoms.xml");
    
    //Reads and parses the XML
    Document doc = builder.build(ins);
    
    //Selects the first two Numbers that are children of the RandomNumbers element
    //It uses 1 - based index not 0 - based
    Nodes nums = doc.query("//RandomNumbers/Number[position() < 3]");
    
    for (int i = ; i < nums.size() ; i ++) {
      System.out.println(nums.get(i).getValue());  
    }
  }

}
   

It gives the following output,
File Name  :  OUTPUT



 
  


  
bl  br