KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > util > DOMUtil


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.jbi.util;
18
19 import org.apache.commons.logging.Log;
20 import org.apache.commons.logging.LogFactory;
21 import org.w3c.dom.Attr JavaDoc;
22 import org.w3c.dom.Document JavaDoc;
23 import org.w3c.dom.Element JavaDoc;
24 import org.w3c.dom.NamedNodeMap JavaDoc;
25 import org.w3c.dom.Node JavaDoc;
26 import org.w3c.dom.NodeList JavaDoc;
27
28 import javax.xml.namespace.QName JavaDoc;
29 import javax.xml.transform.OutputKeys JavaDoc;
30 import javax.xml.transform.Transformer JavaDoc;
31 import javax.xml.transform.TransformerException JavaDoc;
32 import javax.xml.transform.TransformerFactory JavaDoc;
33 import javax.xml.transform.dom.DOMSource JavaDoc;
34 import javax.xml.transform.stream.StreamResult JavaDoc;
35
36 import java.io.StringWriter JavaDoc;
37
38 /**
39  * A collection of W3C DOM helper methods
40  *
41  * @version $Revision: 438853 $
42  */

43 public class DOMUtil {
44     private static final Log log = LogFactory.getLog(DOMUtil.class);
45
46     /**
47      * Returns the text of the element
48      */

49     public static String JavaDoc getElementText(Element JavaDoc element) {
50         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
51         NodeList JavaDoc nodeList = element.getChildNodes();
52         for (int i = 0, size = nodeList.getLength(); i < size; i++) {
53             Node JavaDoc node = nodeList.item(i);
54             if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {
55                 buffer.append(node.getNodeValue());
56             }
57         }
58         return buffer.toString();
59     }
60
61     /**
62      * Moves the content of the given element to the given element
63      */

64     public static void moveContent(Element JavaDoc from, Element JavaDoc to) {
65         // lets move the child nodes across
66
NodeList JavaDoc childNodes = from.getChildNodes();
67         while (childNodes.getLength() > 0) {
68             Node JavaDoc node = childNodes.item(0);
69             from.removeChild(node);
70             to.appendChild(node);
71         }
72     }
73
74     /**
75      * Copy the attribues on one element to the other
76      */

77     public static void copyAttributes(Element JavaDoc from, Element JavaDoc to) {
78         // lets copy across all the remainingattributes
79
NamedNodeMap JavaDoc attributes = from.getAttributes();
80         for (int i = 0, size = attributes.getLength(); i < size; i++) {
81             Attr JavaDoc node = (Attr JavaDoc) attributes.item(i);
82             to.setAttributeNS(node.getNamespaceURI(), node.getName(), node.getValue());
83         }
84     }
85
86     /**
87      * A helper method useful for debugging and logging which will convert the given DOM node into XML text
88      */

89     public static String JavaDoc asXML(Node JavaDoc node) throws TransformerException JavaDoc {
90         Transformer JavaDoc transformer = TransformerFactory.newInstance().newTransformer();
91         StringWriter JavaDoc buffer = new StringWriter JavaDoc();
92         transformer.transform(new DOMSource JavaDoc(node), new StreamResult JavaDoc(buffer));
93         return buffer.toString();
94     }
95
96     /**
97      * A helper method useful for debugging and logging which will convert the given DOM node into XML text
98      */

99     public static String JavaDoc asIndentedXML(Node JavaDoc node) throws TransformerException JavaDoc {
100         Transformer JavaDoc transformer = TransformerFactory.newInstance().newTransformer();
101         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
102         StringWriter JavaDoc buffer = new StringWriter JavaDoc();
103         transformer.transform(new DOMSource JavaDoc(node), new StreamResult JavaDoc(buffer));
104         return buffer.toString();
105     }
106
107     /**
108      * Adds the child element with the given text
109      */

110     public static void addChildElement(Element JavaDoc element, String JavaDoc name, Object JavaDoc textValue) {
111         Document JavaDoc document = element.getOwnerDocument();
112         Element JavaDoc child = document.createElement(name);
113         element.appendChild(child);
114         if (textValue != null) {
115             String JavaDoc text = textValue.toString();
116             child.appendChild(document.createTextNode(text));
117         }
118     }
119
120     /**
121      * Creates a QName instance from the given namespace context for the given qualifiedName
122      *
123      * @param element the element to use as the namespace context
124      * @param qualifiedName the fully qualified name
125      * @return the QName which matches the qualifiedName
126      */

127     public static QName JavaDoc createQName(Element JavaDoc element, String JavaDoc qualifiedName) {
128         int index = qualifiedName.indexOf(':');
129         if (index >= 0) {
130             String JavaDoc prefix = qualifiedName.substring(0, index);
131             String JavaDoc localName = qualifiedName.substring(index + 1);
132             String JavaDoc uri = recursiveGetAttributeValue(element, "xmlns:" + prefix);
133             return new QName JavaDoc(uri, localName, prefix);
134         }
135         else {
136             String JavaDoc uri = recursiveGetAttributeValue(element, "xmlns");
137             if (uri != null) {
138                 return new QName JavaDoc(uri, qualifiedName);
139             }
140             return new QName JavaDoc(qualifiedName);
141         }
142     }
143
144     /**
145      * Recursive method to find a given attribute value
146      */

147     public static String JavaDoc recursiveGetAttributeValue(Element JavaDoc element, String JavaDoc attributeName) {
148         String JavaDoc answer = null;
149         try {
150             answer = element.getAttribute(attributeName);
151         }
152         catch (Exception JavaDoc e) {
153             if (log.isTraceEnabled()) {
154                 log.trace("Caught exception looking up attribute: " + attributeName + " on element: " + element + ". Cause: " + e, e);
155             }
156         }
157         if (answer == null || answer.length() == 0) {
158             Node JavaDoc parentNode = element.getParentNode();
159             if (parentNode instanceof Element JavaDoc) {
160                 return recursiveGetAttributeValue((Element JavaDoc) parentNode, attributeName);
161             }
162         }
163         return answer;
164     }
165
166     /**
167      * Get the first child element
168      * @param parent
169      * @return
170      */

171     public static Element JavaDoc getFirstChildElement(Node JavaDoc parent) {
172         NodeList JavaDoc childs = parent.getChildNodes();
173         for (int i = 0; i < childs.getLength(); i++) {
174             Node JavaDoc child = childs.item(i);
175             if (child instanceof Element JavaDoc) {
176                 return (Element JavaDoc) child;
177             }
178         }
179         return null;
180     }
181     
182     /**
183      * Get the next sibling element
184      * @param el
185      * @return
186      */

187     public static Element JavaDoc getNextSiblingElement(Element JavaDoc el) {
188         for (Node JavaDoc n = el.getNextSibling(); n != null; n = n.getNextSibling()) {
189             if (n instanceof Element JavaDoc) {
190                 return (Element JavaDoc) n;
191             }
192         }
193         return null;
194     }
195     
196     /**
197      * Build a QName from the element name
198      * @param el
199      * @return
200      */

201     public static QName JavaDoc getQName(Element JavaDoc el) {
202         if (el == null) {
203             return null;
204         } else if (el.getPrefix() != null) {
205             return new QName JavaDoc(el.getNamespaceURI(), el.getLocalName(), el.getPrefix());
206         } else {
207             return new QName JavaDoc(el.getNamespaceURI(), el.getLocalName());
208         }
209     }
210     
211 }
212
Popular Tags