KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > XMLUtil


1 package jodd.util;
2
3 import java.util.HashMap;
4 import java.util.Map;
5 import java.util.ArrayList;
6 import java.util.List;
7
8 import org.w3c.dom.Document;
9 import org.w3c.dom.Node;
10 import org.w3c.dom.NamedNodeMap;
11 import org.w3c.dom.NodeList;
12
13 import org.apache.xpath.XPathAPI;
14 import javax.xml.transform.TransformerException;
15
16 /**
17  * Some XML and XPath utilities.
18  */

19 public class XMLUtil {
20
21     /**
22      * Returns a map of node attributes. All non-attribute nodes are ignored.
23      *
24      * @param node node
25      *
26      * @return map of node attributes
27      */

28     public static Map getNodeAttributes(Node node) {
29         HashMap attrs = new HashMap();
30         NamedNodeMap nmm = node.getAttributes();
31         for (int j = 0; j < nmm.getLength(); j++) {
32             Node attribute = nmm.item(j);
33             if (attribute.getNodeType() != Node.ATTRIBUTE_NODE) {
34                 continue;
35             }
36             attrs.put(attribute.getNodeName(), attribute.getNodeValue());
37         }
38         return attrs;
39     }
40
41     /**
42      * Returns a list of all contained nodes in the node list. All non-element nodes are ignored.
43      *
44      * @param nodeList node list
45      *
46      * @return list of contained nodes
47      */

48     public static List getNodes(NodeList nodeList) {
49         ArrayList nodes = new ArrayList();
50         for (int k = 0; k < nodeList.getLength(); k++) {
51             Node node = nodeList.item(k);
52             if (node.getNodeType() != Node.ELEMENT_NODE) {
53                 continue;
54             }
55             nodes.add(node);
56         }
57         return nodes;
58     }
59
60     /**
61      * Returns a list of all contained nodes in the node list.
62      *
63      * @param doc xml document
64      * @param xpath xpath
65      *
66      * @return list of contained nodes
67      * @exception TransformerException
68      */

69     public static List getNodes(Document doc, String xpath) throws TransformerException {
70         return getNodes(XPathAPI.selectNodeList(doc, xpath));
71     }
72
73 }
74
Popular Tags