01: /*
02: * hgcommons 7
03: * Hammurapi Group Common Library
04: * Copyright (C) 2003 Hammurapi Group
05: *
06: * This program is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public
08: * License as published by the Free Software Foundation; either
09: * version 2 of the License, or (at your option) any later version.
10: *
11: * This program is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * Lesser General Public License for more details.
15: *
16: * You should have received a copy of the GNU Lesser General Public
17: * License along with this library; if not, write to the Free Software
18: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19: *
20: * URL: http://www.hammurapi.biz/hammurapi-biz/ef/xmenu/hammurapi-group/products/products/hgcommons/index.html
21: * e-Mail: support@hammurapi.biz
22: */
23:
24: package biz.hammurapi.xml.dom;
25:
26: import javax.xml.transform.TransformerException;
27:
28: import org.apache.xpath.CachedXPathAPI;
29: import org.w3c.dom.Document;
30: import org.w3c.dom.Element;
31: import org.w3c.dom.Node;
32: import org.w3c.dom.NodeList;
33: import org.w3c.dom.Text;
34:
35: /**
36: * @author Pavel Vlasov
37: * @version $Revision: 1.4 $
38: */
39: public class AbstractDomObject {
40:
41: public static String getElementText(Element root, String child,
42: CachedXPathAPI cxpa) throws TransformerException {
43: Node n = (cxpa == null ? new CachedXPathAPI() : cxpa)
44: .selectSingleNode(root, child);
45: return n == null ? null : getElementText(n);
46: }
47:
48: /**
49: * @param node
50: * @return Concatenation of all text sub
51: */
52: public static String getElementText(Node node) {
53: StringBuffer ret = new StringBuffer();
54: NodeList childNodes = node.getChildNodes();
55: for (int i = 0, j = childNodes.getLength(); i < j; i++) {
56: Node item = childNodes.item(i);
57: if (item instanceof Text) {
58: ret.append(item.getNodeValue());
59: }
60: }
61: return ret.toString();
62: }
63:
64: /**
65: * Adds element with text if text is not null.
66: * @param root
67: * @param name
68: * @param text
69: */
70: public static Element addTextElement(Element root, String name,
71: String text) {
72: if (text != null) {
73: Element e = addElement(root, name);
74: e.appendChild(root.getOwnerDocument().createTextNode(text));
75: return e;
76: }
77: return null;
78: }
79:
80: /**
81: * Adds element with specified name.
82: * @param root
83: * @param name
84: * @return
85: */
86: public static Element addElement(Node root, String name) {
87: Document doc = root instanceof Document ? (Document) root
88: : root.getOwnerDocument();
89: Element ret = doc.createElement(name);
90: root.appendChild(ret);
91: return ret;
92: }
93: }
|