5.18.2011

xpath util

Why, oh why do I need to create a document every time I want to xpath evaluate something simple?

So I creates XpathUtil

Usage:
NodeList nodes = 
(NodeList)new XPathUtil(file).evaluate("//directoryToRead/text()");

package com.util;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

public class XPathUtil {

 private Log log = LogFactory.getLog(getClass().getName());

 private Document doc = null;

 private XPath xpath = null;

 public XPathUtil(File inputFile) {
  // begin:Recipe code to get xpath factory
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true); // never forget this!
  DocumentBuilder builder;
  try {
   builder = factory.newDocumentBuilder();

   doc = builder.parse(inputFile);
  } catch (Exception e) {
   log.error(e.getMessage(), e);
   throw new RuntimeException(e.getMessage(), e);
  }
  XPathFactory xPathFactory = XPathFactory.newInstance();
  xpath = xPathFactory.newXPath();
  // end: recipe code to get xpath
 }

 public Object evaluate(String xPathExpression) {
  XPathExpression expr;
  Object result;
  try {
   expr = xpath.compile(xPathExpression);

   result = expr.evaluate(doc, XPathConstants.NODESET);
  } catch (XPathExpressionException e) {
   log.error(e.getMessage(), e);
   throw new RuntimeException(e.getMessage(), e);
  }

  return result;
 }
}

No hay comentarios.:

Publicar un comentario