01: /*
02: * Copyright 2005 Joe Walker
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: package org.directwebremoting.drapgen.util;
17:
18: import nu.xom.Element;
19: import nu.xom.Elements;
20: import nu.xom.Node;
21: import nu.xom.Nodes;
22: import nu.xom.XPathException;
23:
24: /**
25: * @author Joe Walker [joe at getahead dot ltd dot uk]
26: */
27: public class XomHelper {
28: public interface ElementBlock {
29: public void use(Element element);
30: }
31:
32: public static String queryValue(Node doc, String xpath) {
33: Nodes nodes = doc.query(xpath);
34:
35: if (nodes.size() == 0) {
36: return null;
37: }
38:
39: if (nodes.size() == 1) {
40: return nodes.get(0).getValue();
41: }
42:
43: throw new XPathException(
44: "XPath expression returned more than 1 node");
45: }
46:
47: public static int query(Node doc, String xpath, ElementBlock functor) {
48: Nodes nodes = doc.query(xpath);
49: for (int i = 0; i < nodes.size(); i++) {
50: Element element = (Element) nodes.get(i);
51: functor.use(element);
52: }
53: return nodes.size();
54: }
55:
56: public static int getChildElements(Element element, String name,
57: ElementBlock functor) {
58: Elements children = element.getChildElements(name);
59: for (int i = 0; i < children.size(); i++) {
60: Element child = children.get(i);
61: functor.use(child);
62: }
63: return children.size();
64: }
65: }
|