01: /*
02: * Copyright (c) 2002-2006 by OpenSymphony
03: * All rights reserved.
04: */
05: package com.opensymphony.xwork.config.providers;
06:
07: import org.w3c.dom.Element;
08: import org.w3c.dom.Node;
09: import org.w3c.dom.NodeList;
10:
11: import java.util.Iterator;
12: import java.util.Map;
13: import java.util.LinkedHashMap;
14:
15: /**
16: * XML utilities.
17: *
18: * @author Mike
19: * @author tmjee
20: */
21: public class XmlHelper {
22:
23: /**
24: * This method will find all the parameters under this <code>paramsElement</code> and return them as
25: * Map<String, String>. For example,
26: * <pre>
27: * <result ... >
28: * <param name="param1">value1</param>
29: * <param name="param2">value2</param>
30: * <param name="param3">value3</param>
31: * </result>
32: * </pre>
33: * will returns a Map<String, String> with the following key, value pairs :-
34: * <ul>
35: * <li>param1 - value1</li>
36: * <li>param2 - value2</li>
37: * <li>param3 - value3</li>
38: * </ul>
39: *
40: * @param paramsElement
41: * @return
42: */
43: public static Map getParams(Element paramsElement) {
44: LinkedHashMap params = new LinkedHashMap();
45:
46: if (paramsElement == null) {
47: return params;
48: }
49:
50: NodeList childNodes = paramsElement.getChildNodes();
51: for (int i = 0; i < childNodes.getLength(); i++) {
52: Node childNode = childNodes.item(i);
53:
54: if ((childNode.getNodeType() == Node.ELEMENT_NODE)
55: && "param".equals(childNode.getNodeName())) {
56: Element paramElement = (Element) childNode;
57: String paramName = paramElement.getAttribute("name");
58:
59: String val = getContent(paramElement);
60: if (val.length() > 0) {
61: params.put(paramName, val);
62: }
63: }
64: }
65: return params;
66: }
67:
68: /**
69: * This method will return the content of this particular <code>element</code>.
70: * For example,
71: *
72: * <pre>
73: * <result>something_1</result>
74: * </pre>
75: * When the {@link org.w3c.dom.Element} <code><result></code> is passed in as
76: * argument (<code>element</code> to this method, it returns the content of it,
77: * namely, <code>something_1</code> in the example above.
78: *
79: * @return
80: */
81: public static String getContent(Element element) {
82: StringBuffer paramValue = new StringBuffer();
83: NodeList childNodes = element.getChildNodes();
84: for (int j = 0; j < childNodes.getLength(); j++) {
85: Node currentNode = childNodes.item(j);
86: if (currentNode != null
87: && currentNode.getNodeType() == Node.TEXT_NODE) {
88: String val = currentNode.getNodeValue();
89: if (val != null) {
90: paramValue.append(val.trim());
91: }
92: }
93: }
94: String val = paramValue.toString().trim();
95: return val;
96: }
97: }
|