01: /*
02: * Copyright 2004-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.compass.core.xml.javax;
18:
19: import javax.xml.xpath.XPathExpression;
20: import javax.xml.xpath.XPathFactory;
21:
22: import org.compass.core.util.DomUtils;
23: import org.compass.core.xml.XmlObject;
24: import org.compass.core.xml.XmlXPathExpression;
25: import org.w3c.dom.Element;
26: import org.w3c.dom.Node;
27:
28: /**
29: * A java 5 implementation of {@link XmlObject} wrapping a {@link Node}.
30: *
31: * @author kimchy
32: */
33: public class NodeXmlObject implements XmlObject {
34:
35: private Node node;
36:
37: /**
38: * Constructs a new xml object using the given {@link Node}.
39: */
40: public NodeXmlObject(Node node) {
41: this .node = node;
42: }
43:
44: /**
45: * Returns the node name, if the {@link org.w3c.dom.Node#getLocalName()} is not <code>null</code>
46: * will return it, otherwise will return {@link org.w3c.dom.Node#getNodeName()}.
47: */
48: public String getName() {
49: if (node.getLocalName() != null) {
50: return node.getLocalName();
51: }
52: return node.getNodeName();
53: }
54:
55: /**
56: * Returns the node value, using {@link org.w3c.dom.Node#getNodeValue()} with the
57: * exception of element, which has special handling using {@link DomUtils#getTextValue(org.w3c.dom.Element)}.
58: */
59: public String getValue() {
60: if (node.getNodeType() == Node.ELEMENT_NODE) {
61: return DomUtils.getTextValue((Element) node);
62: }
63: return node.getNodeValue();
64: }
65:
66: /**
67: * Compiles and selects the given xpath expression.
68: */
69: public XmlObject[] selectPath(String path) throws Exception {
70: return compile(path).select(this );
71: }
72:
73: /**
74: * Returns <code>true</code> since xpath expression compilation is supported.
75: */
76: public boolean canCompileXpath() {
77: return true;
78: }
79:
80: /**
81: * Compiles the given xpath expression.
82: */
83: public XmlXPathExpression compile(String path) throws Exception {
84: XPathExpression xPathExpression = XPathFactory.newInstance()
85: .newXPath().compile(path);
86: return new XPathXmlXPathExpression(xPathExpression);
87: }
88:
89: /**
90: * Returns the {@link Node} this xml object wraps.
91: */
92: public Node getNode() {
93: return node;
94: }
95:
96: }
|