Guest User

XPathTest

a guest
May 8th, 2012
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.io.IOException;
  2.  
  3. import javax.xml.parsers.DocumentBuilder;
  4. import javax.xml.parsers.DocumentBuilderFactory;
  5. import javax.xml.parsers.ParserConfigurationException;
  6. import javax.xml.xpath.XPath;
  7. import javax.xml.xpath.XPathConstants;
  8. import javax.xml.xpath.XPathExpressionException;
  9. import javax.xml.xpath.XPathFactory;
  10.  
  11. import org.w3c.dom.Document;
  12. import org.w3c.dom.NodeList;
  13. import org.xml.sax.SAXException;
  14.  
  15.  
  16. public class XPathTest {
  17.  
  18.    
  19.     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException{
  20.        
  21.         final String entryXpath = "//entry/*/text()";
  22.         final String contentXpath = "//content/*";
  23.        
  24.         DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  25.         domFactory.setNamespaceAware(false);
  26.        
  27.         DocumentBuilder builder = domFactory.newDocumentBuilder();
  28.         Document doc = builder.parse("/Users/nathanschwermann/Desktop/blog.xml");
  29.        
  30.         XPathFactory factory = XPathFactory.newInstance();
  31.         XPath xpath = factory.newXPath();
  32.        
  33.         javax.xml.xpath.XPathExpression expr = xpath.compile(contentXpath);
  34.         Object result = expr.evaluate(doc, XPathConstants.STRING);
  35.         System.out.println((String)result);
  36.        
  37.         expr = xpath.compile(entryXpath);
  38.         result = expr.evaluate(doc, XPathConstants.NODESET);
  39.         NodeList nodes = (NodeList)result;
  40.         System.out.println("----======printing nodes=====------");
  41.         for(int i = 0; i < nodes.getLength(); i++){
  42.             System.out.println(nodes.item(i).getNodeValue());
  43.         }
  44.  
  45.     }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment