java/alt2xml-out-xpath/src/cz/frantovo/alt2xml/out/xpath/XPathAction.java
changeset 63 89acb486bb52
parent 49 bec481687c1b
child 64 e2c691eedf4d
     1.1 --- a/java/alt2xml-out-xpath/src/cz/frantovo/alt2xml/out/xpath/XPathAction.java	Wed Sep 03 19:53:14 2014 +0200
     1.2 +++ b/java/alt2xml-out-xpath/src/cz/frantovo/alt2xml/out/xpath/XPathAction.java	Thu Sep 04 00:39:11 2014 +0200
     1.3 @@ -17,25 +17,49 @@
     1.4   */
     1.5  package cz.frantovo.alt2xml.out.xpath;
     1.6  
     1.7 -import cz.frantovo.alt2xml.out.AbstractAction;
     1.8 +import cz.frantovo.alt2xml.out.AbstractDOMAction;
     1.9  import cz.frantovo.alt2xml.out.ActionContext;
    1.10  import cz.frantovo.alt2xml.out.OutputActionException;
    1.11 -import javax.xml.parsers.SAXParser;
    1.12 -import org.xml.sax.InputSource;
    1.13 +import java.io.PrintWriter;
    1.14 +import javax.xml.transform.dom.DOMResult;
    1.15 +import javax.xml.xpath.XPath;
    1.16 +import javax.xml.xpath.XPathExpression;
    1.17 +import javax.xml.xpath.XPathExpressionException;
    1.18 +import javax.xml.xpath.XPathFactory;
    1.19 +import org.w3c.dom.Node;
    1.20  
    1.21  /**
    1.22   *
    1.23   * @author Ing. František Kučera (frantovo.cz)
    1.24   */
    1.25 -public class XPathAction extends AbstractAction {
    1.26 +public class XPathAction extends AbstractDOMAction {
    1.27  
    1.28  	public XPathAction(ActionContext actionContext) {
    1.29  		super(actionContext);
    1.30  	}
    1.31  
    1.32  	@Override
    1.33 -	public void run(SAXParser parser, InputSource source) throws OutputActionException {
    1.34 -		// TODO: XPath
    1.35 -		throw new UnsupportedOperationException("Not supported yet.");
    1.36 +	public void run(DOMResult domResult) throws OutputActionException {
    1.37 +
    1.38 +		// TODO: reuse
    1.39 +		XPathFactory xpf = XPathFactory.newInstance();
    1.40 +		XPath xp = xpf.newXPath();
    1.41 +
    1.42 +		// String expressionString = getActionContext().
    1.43 +		String expressionString = "1+1";
    1.44 +		expressionString = "//property[@name='ccc']";
    1.45 +
    1.46 +		try {
    1.47 +			XPathExpression xpe = xp.compile(expressionString);
    1.48 +
    1.49 +			String result = xpe.evaluate(domResult.getNode());
    1.50 +
    1.51 +			try (PrintWriter out = new PrintWriter(getActionContext().getOutputStream())) {
    1.52 +				out.println(result);
    1.53 +			}
    1.54 +
    1.55 +		} catch (XPathExpressionException e) {
    1.56 +			throw new OutputActionException("Unable to compile or evaluate XPath: " + expressionString, e);
    1.57 +		}
    1.58  	}
    1.59  }