01: /*
02: * selectSingleNode.java
03: *
04: * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.xml;
10:
11: import com.sun.org.apache.xpath.internal.XPathAPI;
12: import pnuts.lang.PnutsFunction;
13: import pnuts.lang.Context;
14: import pnuts.lang.PnutsException;
15: import org.w3c.dom.Node;
16: import javax.xml.transform.TransformerException;
17: import javax.xml.xpath.XPath;
18: import javax.xml.xpath.XPathConstants;
19: import javax.xml.xpath.XPathFactory;
20:
21: public class selectSingleNode extends PnutsFunction {
22:
23: public selectSingleNode() {
24: super ("selectSingleNode");
25: }
26:
27: public boolean defined(int nargs) {
28: return nargs == 2 || nargs == 3;
29: }
30:
31: protected Object exec(Object[] args, Context context) {
32: try {
33: int nargs = args.length;
34: if (nargs == 2) {
35: XPath xpath = XPathFactory.newInstance().newXPath();
36: if (args[0] instanceof Node) {
37: return xpath.evaluate((String) args[1], args[0],
38: XPathConstants.NODE);
39: } else {
40: return xpath.evaluate((String) args[1], Util
41: .inputSource(args[0], context),
42: XPathConstants.NODE);
43: }
44: } else if (nargs == 3) {
45: XPath xpath = XPathFactory.newInstance().newXPath();
46: if (args[0] instanceof Node) {
47: return xpath.evaluate((String) args[1], args[0],
48: XPathConstants.NODE);
49: } else {
50: return xpath.evaluate((String) args[1], Util
51: .inputSource(args[0], context),
52: XPathConstants.NODE);
53: }
54: } else {
55: undefined(args, context);
56: return null;
57: }
58: } catch (Exception e) {
59: throw new PnutsException(e, context);
60: }
61: }
62:
63: public String toString() {
64: return "function selectSingleNode(Node, String {, Node })";
65: }
66: }
|