Java Reference
In-Depth Information
Example 20-10. XPathDemo.java
/**
* Simple demo of XPath, supported in JAXP (in JavaSE package javax.xml.xpath)
*/
public
public class
class XPathDemo
XPathDemo {
public
public static
static void
void main ( String [] args ) throws
throws Exception {
DocumentBuilder parser =
DocumentBuilderFactory . newInstance (). newDocumentBuilder ();
String doc = "<?xml version='1.0'?>" +
"<section><sectiontitle>A Discourse of Numbers</sectiontitle>" +
"<sectionnumber>1.2</sectionnumber>" +
"<SC>Introduction</SC><p></p></section>" ;
Document document =
parser . parse ( new
new ByteArrayInputStream ( doc . getBytes ()));
// Evaluate the XPath expression against the Document
XPath xpath = XPathFactory . newInstance (). newXPath ();
String expression = "/section/sectionnumber" ;
Number secNum = ( Number ) xpath . evaluate (
expression , document , XPathConstants . NUMBER );
System . out . printf ( "Section number = %s (a %s)" ,
secNum , secNum . getClass (). getName ());
}
}
Create a Document parser.
He re the input XML document is a hardcoded String.
Cr eate a Document from the XML document created in .
Cr eate an XPath execution wrapper.
Sp ecify the string to match; this says to find the sectionnumber element inside a sec-
tion element.
Fi nally, evaluate the XPath expression.
 
 
 
 
 
 
 
Search WWH ::




Custom Search