XML > XOM > Xpath Query Namespace
Xpath Query Namespace
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 with namespace using XPath expression.
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;
import nu.xom.XPathContext;
public class XpathQuery2 {
/**
* @param args
* @throws IOException
* @throws ParsingException
* @throws ValidityException
*/
public static void main ( String [] args ) throws ValidityException, ParsingException, IOException {
Builder builder = new Builder () ;
InputStream ins = XpathQuery2. class .getClassLoader ()
.getResourceAsStream ( "ns_randoms.xml" ) ;
//Reads and parses the XML
XPathContext context = new XPathContext ( "btc" , "http://bethecoder.com" ) ;
Document doc = builder.build ( ins ) ;
//Get all numbers
Nodes nodes = doc.query ( "//btc:RandomNumbers/btc:Number" , context ) ;
for ( int i = 0 ; i < nodes.size () ; i ++ ) {
System.out.println ( nodes.get ( i ) .getValue ()) ;
}
}
}
It gives the following output,