KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jnlp > sample > servlet > XMLParsing


1 /*
2  * @(#)XMLParsing.java 1.6 05/11/17
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 package jnlp.sample.servlet;
38
39 import javax.xml.parsers.*;
40 import java.util.ArrayList JavaDoc;
41 import java.util.List JavaDoc;
42 import org.xml.sax.*;
43 import org.w3c.dom.*;
44
45 /** Contains handy methods for looking up information
46  * stored in XMLNodes.
47  */

48 public class XMLParsing {
49        
50     public static XMLNode convert(Node n) {
51         if (n == null) {
52         return null;
53         } else if (n instanceof Text) {
54         Text tn = (Text)n;
55         return new XMLNode(tn.getNodeValue());
56         } else if (n instanceof Element) {
57         Element en = (Element)n;
58         
59         XMLAttribute xmlatts = null;
60         NamedNodeMap attributes = en.getAttributes();
61         for(int i = attributes.getLength() - 1; i >= 0; i--) {
62         Attr ar = (Attr)attributes.item(i);
63         xmlatts = new XMLAttribute(ar.getName(), ar.getValue(), xmlatts);
64         }
65         
66         // Convert childern
67
XMLNode thisNode = new XMLNode(en.getNodeName(), xmlatts, null, null);;
68         XMLNode last = null;
69         Node nn = en.getFirstChild();
70         while(nn != null) {
71         if (thisNode.getNested() == null) {
72             last = convert(nn);
73             thisNode.setNested(last);
74         } else {
75             XMLNode nnode = convert(nn);
76             last.setNext(nnode);
77             last = nnode;
78         }
79         last.setParent(thisNode);
80         nn = nn.getNextSibling();
81         }
82         
83         return thisNode;
84         }
85         return null;
86     }
87     
88     /** Returns true if the path exists in the document, otherwise false */
89     static public boolean isElementPath(XMLNode root, String JavaDoc path) {
90         return findElementPath(root, path) != null;
91     }
92     
93     
94     /** Returns a string describing the current location in the DOM */
95     static public String JavaDoc getPathString(XMLNode e) {
96         return (e == null || !(e.isElement())) ? "" : getPathString(e.getParent()) + "<" + e.getName() + ">";
97     }
98     
99     
100     /** Like getElementContents(...) but with a defaultValue of null */
101     static public String JavaDoc getElementContent(XMLNode root, String JavaDoc path) {
102         return getElementContent(root, path, null);
103     }
104     
105     /** Like getElementContents(...) but with a defaultValue of null */
106     static public String JavaDoc[] getMultiElementContent(XMLNode root, String JavaDoc path) {
107         final List JavaDoc list = new ArrayList JavaDoc();
108     visitElements(root, path, new ElementVisitor() {
109             public void visitElement(XMLNode n) {
110             String JavaDoc value = getElementContent(n, "");
111             if (value != null) list.add(value);
112             }
113         });
114     if (list.size() == 0) return null;
115     return (String JavaDoc[])list.toArray(new String JavaDoc[list.size()]);
116     }
117     
118     /** Returns the value of the last element tag in the path, e.g., <..><tag>value</tag>. The DOM is assumes
119      * to be normalized. If no value is found, the defaultvalue is returned
120      */

121     static public String JavaDoc getElementContent(XMLNode root, String JavaDoc path, String JavaDoc defaultvalue) {
122         XMLNode e = findElementPath(root, path);
123     if (e == null) return defaultvalue;
124         XMLNode n = e.getNested();
125         if (n != null && !n.isElement()) return n.getName();
126     return defaultvalue;
127     }
128     
129     /** Parses a path string of the form <tag1><tag2><tag3> and returns the specific Element
130      * node for that tag, or null if it does not exist. If multiple elements exists with same
131      * path the first is returned
132      */

133     static public XMLNode findElementPath(XMLNode elem, String JavaDoc path) {
134     // End condition. Root null -> path does not exist
135
if (elem == null) return null;
136     // End condition. String empty, return current root
137
if (path == null || path.length() == 0) return elem;
138     
139     // Strip of first tag
140
int idx = path.indexOf('>');
141     String JavaDoc head = path.substring(1, idx);
142     String JavaDoc tail = path.substring(idx + 1);
143     return findElementPath(findChildElement(elem, head), tail);
144     }
145     
146     /** Returns an child element with the current tag name or null. */
147     static public XMLNode findChildElement(XMLNode elem, String JavaDoc tag) {
148     XMLNode n = elem.getNested();
149     while(n != null) {
150         if (n.isElement() && n.getName().equals(tag)) return n;
151         n = n.getNext();
152     }
153     return null;
154     }
155     
156     /** Iterator class */
157     public abstract static class ElementVisitor {
158     abstract public void visitElement(XMLNode e);
159     }
160     
161     /** Visits all elements which matches the <path>. The iteration is only
162      * done on the last elment in the path.
163      */

164     static public void visitElements(XMLNode root, String JavaDoc path, ElementVisitor ev) {
165     // Get last element in path
166
int idx = path.lastIndexOf('<');
167     String JavaDoc head = path.substring(0, idx);
168     String JavaDoc tag = path.substring(idx + 1, path.length() - 1);
169     
170     XMLNode elem = findElementPath(root, head);
171     if (elem == null) return;
172     
173     // Iterate through all child nodes
174
XMLNode n = elem.getNested();
175     while(n != null) {
176         if (n.isElement() && n.getName().equals(tag)) {
177         ev.visitElement(n);
178         }
179         n = n.getNext();
180     }
181     }
182     
183     static public void visitChildrenElements(XMLNode elem, ElementVisitor ev) {
184     // Iterate through all child nodes
185
XMLNode n = elem.getNested();
186     while(n != null) {
187         if (n.isElement()) ev.visitElement(n);
188         n = n.getNext();
189     }
190     }
191 }
192
193
Popular Tags