KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > soap > util > xml > DOMUtils


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2000 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "SOAP" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 2000, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package org.apache.soap.util.xml;
59
60 import org.w3c.dom.*;
61
62 /**
63  * @author Matthew J. Duftler
64  * @author Sanjiva Weerawarana
65  */

66 public class DOMUtils {
67   /**
68    * The namespaceURI represented by the prefix <code>xmlns</code>.
69    */

70   private static String JavaDoc NS_URI_XMLNS = "http://www.w3.org/2000/xmlns/";
71
72   /**
73    * Returns the value of an attribute of an element. Returns null
74    * if the attribute is not found (whereas Element.getAttribute
75    * returns "" if an attrib is not found).
76    *
77    * @param el Element whose attrib is looked for
78    * @param attrName name of attribute to look for
79    * @return the attribute value
80    */

81   static public String JavaDoc getAttribute (Element el, String JavaDoc attrName) {
82     String JavaDoc sRet = null;
83     Attr attr = el.getAttributeNode(attrName);
84
85     if (attr != null) {
86       sRet = attr.getValue();
87     }
88     return sRet;
89   }
90
91   /**
92    * Returns the value of an attribute of an element. Returns null
93    * if the attribute is not found (whereas Element.getAttributeNS
94    * returns "" if an attrib is not found).
95    *
96    * @param el Element whose attrib is looked for
97    * @param namespaceURI namespace URI of attribute to look for
98    * @param localPart local part of attribute to look for
99    * @return the attribute value
100    */

101   static public String JavaDoc getAttributeNS (Element el,
102                                        String JavaDoc namespaceURI,
103                                        String JavaDoc localPart) {
104     String JavaDoc sRet = null;
105     Attr attr = el.getAttributeNodeNS (namespaceURI, localPart);
106
107     if (attr != null) {
108       sRet = attr.getValue ();
109     }
110
111     return sRet;
112   }
113
114   /**
115    * Concat all the text and cdata node children of this elem and return
116    * the resulting text.
117    *
118    * @param parentEl the element whose cdata/text node values are to
119    * be combined.
120    * @return the concatanated string.
121    */

122   static public String JavaDoc getChildCharacterData (Element parentEl) {
123     if (parentEl == null) {
124       return null;
125     }
126     Node tempNode = parentEl.getFirstChild();
127     StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
128     CharacterData charData;
129
130     while (tempNode != null) {
131       switch (tempNode.getNodeType()) {
132         case Node.TEXT_NODE :
133         case Node.CDATA_SECTION_NODE : charData = (CharacterData)tempNode;
134                                        strBuf.append(charData.getData());
135                                        break;
136       }
137       tempNode = tempNode.getNextSibling();
138     }
139     return strBuf.toString();
140   }
141
142   /**
143    * Return the first child element of the given element. Null if no
144    * children are found.
145    *
146    * @param elem Element whose child is to be returned
147    * @return the first child element.
148    */

149   public static Element getFirstChildElement (Element elem) {
150     for (Node n = elem.getFirstChild (); n != null; n = n.getNextSibling ()) {
151       if (n.getNodeType () == Node.ELEMENT_NODE) {
152         return (Element) n;
153       }
154     }
155     return null;
156   }
157
158   /**
159    * Return the next sibling element of the given element. Null if no
160    * more sibling elements are found.
161    *
162    * @param elem Element whose sibling element is to be returned
163    * @return the next sibling element.
164    */

165   public static Element getNextSiblingElement (Element elem) {
166     for (Node n = elem.getNextSibling (); n != null; n = n.getNextSibling ()) {
167       if (n.getNodeType () == Node.ELEMENT_NODE) {
168         return (Element) n;
169       }
170     }
171     return null;
172   }
173
174   /**
175    * Return the first child element of the given element which has the
176    * given attribute with the given value.
177    *
178    * @param elem the element whose children are to be searched
179    * @param attrName the attrib that must be present
180    * @param attrValue the desired value of the attribute
181    *
182    * @return the first matching child element.
183    */

184   public static Element findChildElementWithAttribute (Element elem,
185                    String JavaDoc attrName,
186                    String JavaDoc attrValue) {
187     for (Node n = elem.getFirstChild (); n != null; n = n.getNextSibling ()) {
188       if (n.getNodeType () == Node.ELEMENT_NODE) {
189         if (attrValue.equals (DOMUtils.getAttribute ((Element) n, attrName))) {
190           return (Element) n;
191         }
192       }
193     }
194     return null;
195   }
196
197   /**
198    * Count number of children of a certain type of the given element.
199    *
200    * @param elem the element whose kids are to be counted
201    *
202    * @return the number of matching kids.
203    */

204   public static int countKids (Element elem, short nodeType) {
205     int nkids = 0;
206     for (Node n = elem.getFirstChild (); n != null; n = n.getNextSibling ()) {
207       if (n.getNodeType () == nodeType) {
208         nkids++;
209       }
210     }
211     return nkids;
212   }
213
214   /**
215    * Given a prefix and a node, return the namespace URI that the prefix
216    * has been associated with. This method is useful in resolving the
217    * namespace URI of attribute values which are being interpreted as
218    * QNames. If prefix is null, this method will return the default
219    * namespace.
220    *
221    * @param context the starting node (looks up recursively from here)
222    * @param prefix the prefix to find an xmlns:prefix=uri for
223    *
224    * @return the namespace URI or null if not found
225    */

226   public static String JavaDoc getNamespaceURIFromPrefix (Node context,
227                                                   String JavaDoc prefix) {
228     short nodeType = context.getNodeType ();
229     Node tempNode = null;
230
231     switch (nodeType)
232     {
233       case Node.ATTRIBUTE_NODE :
234       {
235         tempNode = ((Attr) context).getOwnerElement ();
236         break;
237       }
238       case Node.ELEMENT_NODE :
239       {
240         tempNode = context;
241         break;
242       }
243       default :
244       {
245         tempNode = context.getParentNode ();
246         break;
247       }
248     }
249
250     while (tempNode != null && tempNode.getNodeType () == Node.ELEMENT_NODE)
251     {
252       Element tempEl = (Element) tempNode;
253       String JavaDoc namespaceURI = (prefix == null)
254                             ? getAttribute (tempEl, "xmlns")
255                             : getAttributeNS (tempEl, NS_URI_XMLNS, prefix);
256
257       if (namespaceURI != null)
258       {
259         return namespaceURI;
260       }
261       else
262       {
263         tempNode = tempEl.getParentNode ();
264       }
265     }
266
267     return null;
268   }
269
270   public static Element getElementByID(Element el, String JavaDoc id)
271   {
272       if (el == null)
273           return null;
274       String JavaDoc thisId = el.getAttribute("id");
275       if (id.equals(thisId))
276           return el;
277       
278       NodeList list = el.getChildNodes();
279       for (int i = 0; i < list.getLength(); i++) {
280           Node node = list.item(i);
281           if (node instanceof Element) {
282               Element ret = getElementByID((Element)node, id);
283               if (ret != null)
284                   return ret;
285           }
286       }
287       
288       return null;
289   }
290
291   public static QName getQualifiedAttributeValue(Element el,
292                                                  String JavaDoc attrName)
293     throws IllegalArgumentException JavaDoc
294   {
295     String JavaDoc attrValue = DOMUtils.getAttribute(el, attrName);
296
297     if (attrValue != null)
298     {
299       int index = attrValue.indexOf(':');
300       String JavaDoc attrValuePrefix = (index != -1)
301                                      ? attrValue.substring(0, index)
302                                      : null;
303       String JavaDoc attrValueLocalPart = attrValue.substring(index + 1);
304       String JavaDoc attrValueNamespaceURI =
305         DOMUtils.getNamespaceURIFromPrefix(el, attrValuePrefix);
306
307       if (attrValueNamespaceURI != null)
308       {
309         return new QName(attrValueNamespaceURI, attrValueLocalPart);
310       }
311       else
312       {
313         throw new IllegalArgumentException JavaDoc("Unable to determine " +
314                                            "namespace of '" +
315                                            (attrValuePrefix != null
316                                             ? attrValuePrefix + ":"
317                                             : "") + attrValueLocalPart +
318                                            "'.");
319       }
320     }
321     else
322     {
323       return null;
324     }
325   }
326 }
327
Popular Tags