KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > petals > component > common > util > XMLHelper


1 /**
2  * PETALS - PETALS Services Platform.
3  * Copyright (c) 2005 EBM Websourcing, http://www.ebmwebsourcing.com/
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * -------------------------------------------------------------------------
19  * $Id: XMLHelper.java 17:06:54 ddesjardins $
20  * -------------------------------------------------------------------------
21  */

22 package org.objectweb.petals.component.common.util;
23
24 import java.io.ByteArrayInputStream JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.StringWriter JavaDoc;
27
28 import javax.xml.parsers.DocumentBuilder JavaDoc;
29 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
30 import javax.xml.transform.OutputKeys JavaDoc;
31 import javax.xml.transform.Result JavaDoc;
32 import javax.xml.transform.Source JavaDoc;
33 import javax.xml.transform.Transformer JavaDoc;
34 import javax.xml.transform.TransformerException JavaDoc;
35 import javax.xml.transform.TransformerFactory JavaDoc;
36 import javax.xml.transform.dom.DOMResult JavaDoc;
37 import javax.xml.transform.dom.DOMSource JavaDoc;
38 import javax.xml.transform.stream.StreamResult JavaDoc;
39
40 import org.w3c.dom.Document JavaDoc;
41 import org.w3c.dom.NamedNodeMap JavaDoc;
42 import org.w3c.dom.Node JavaDoc;
43 import org.w3c.dom.NodeList JavaDoc;
44
45 import com.sun.org.apache.xpath.internal.NodeSet;
46
47 /**
48  * Util class to manipulate Dom document
49  *
50  * @author ddesjardins - eBMWebsourcing
51  * @author wjoseph - eBMWebsourcing
52  */

53 public class XMLHelper {
54
55     /**
56      * Namespace for the soap 1.1
57      */

58
59     protected XMLHelper() {
60     }
61
62     /**
63      * Create a dom document from a string
64      *
65      * @param source
66      * The input string representing xml flow
67      * @return dom document
68      */

69     public static Document JavaDoc createDocumentFromString(String JavaDoc source) {
70         Document JavaDoc doc = null;
71         try {
72             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory
73                     .newInstance();
74             factory.setNamespaceAware(true);
75             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
76             InputStream JavaDoc is = new ByteArrayInputStream JavaDoc(source.getBytes());
77             doc = builder.parse(is);
78             doc.normalize();
79         } catch (Exception JavaDoc e) {
80             e.printStackTrace();
81         }
82         return doc;
83     }
84
85     /**
86      * Create a String result from a DOM document
87      *
88      * @param document
89      * the DOM Document
90      * @return a String representation of the DOM Document
91      * @throws TransformerException
92      */

93     public static String JavaDoc createStringFromDOMDocument(Document JavaDoc document)
94         throws TransformerException JavaDoc {
95         document.normalize();
96         Source JavaDoc source = new DOMSource JavaDoc(document);
97         StringWriter JavaDoc out = new StringWriter JavaDoc();
98         Result JavaDoc resultStream = new StreamResult JavaDoc(out);
99         TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
100         Transformer JavaDoc transformer;
101         transformer = tFactory.newTransformer();
102         transformer.transform(source, resultStream);
103         String JavaDoc result = out.toString();
104
105         return result;
106     }
107
108     /**
109      * Create a String result from a DOM Node
110      *
111      * @param node
112      * the DOM Node
113      * @return a String representation of the DOM Document
114      * @throws TransformerException
115      */

116     public static String JavaDoc createStringFromDOMNode(Node JavaDoc node)
117         throws TransformerException JavaDoc {
118         // node.normalize();
119
Source JavaDoc source = new DOMSource JavaDoc(node);
120         StringWriter JavaDoc out = new StringWriter JavaDoc();
121         Result JavaDoc resultStream = new StreamResult JavaDoc(out);
122         TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
123         Transformer JavaDoc transformer;
124         transformer = tFactory.newTransformer();
125         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
126         transformer.transform(source, resultStream);
127         String JavaDoc result = out.toString();
128         return result;
129     }
130
131     /**
132      * Create a DOM Node result from an XML Source
133      *
134      * @param node
135      * the XML Source
136      * @return a DOM representation of the XML Document
137      * @throws TransformerException
138      */

139     public static Node JavaDoc createDOMNodeFromSource(Source JavaDoc source)
140         throws TransformerException JavaDoc {
141         DOMResult JavaDoc resultDom = new DOMResult JavaDoc();
142         TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
143         Transformer JavaDoc transformer;
144         transformer = tFactory.newTransformer();
145         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
146         transformer.transform(source, resultDom);
147         Node JavaDoc resultNode = resultDom.getNode();
148         return resultNode;
149     }
150
151     /**
152      * Search for a child with the given nodeName. If recursive, search in all
153      * the child of firdt level, then if not found, search in the 2nd level of
154      * the first child, ...
155      *
156      * @param parent
157      * parent node
158      * @param nodeName
159      * node name
160      * @param recursive
161      * boolean to know if we got through the xml tree
162      * @return a node
163      */

164     public static Node JavaDoc findChild(Node JavaDoc parent, String JavaDoc nodeName, boolean recursive) {
165         parent.normalize();
166         Node JavaDoc result = null;
167         if (parent != null && nodeName != null) {
168             NodeList JavaDoc nl = parent.getChildNodes();
169             for (int i = 0; i < nl.getLength() && result == null; i++) {
170                 if (nodeName.equals(nl.item(i).getNodeName())) {
171                     result = nl.item(i);
172                 }
173             }
174             // now, search recursively if required
175
if (result == null && recursive) {
176                 for (int i = 0; i < nl.getLength() && result == null; i++) {
177                     result = findChild(nl.item(i), nodeName, true);
178                 }
179             }
180         }
181         return result;
182     }
183
184     /**
185      * Search for a child with the given nodeName. If recursive, search in all
186      * the child of firdt level, then if not found, search in the 2nd level of
187      * the first child, ...
188      *
189      * @param parent
190      * parent node
191      * @param namespaceURI
192      * The namespaceURI of the node
193      * @param nodeName
194      * node name
195      * @param recursive
196      * boolean to know if we got through the xml tree
197      * @return a node
198      */

199     public static Node JavaDoc findChild(Node JavaDoc parent, String JavaDoc namespaceURI,
200             String JavaDoc nodeName, boolean recursive) {
201         parent.normalize();
202         String JavaDoc prefix = getPrefixForNamespaceURI(parent, namespaceURI, false);
203         return (findChild(parent, prefix + nodeName, recursive));
204     }
205
206     /**
207      * Search for children with the given nodeName. If recursive, search in all
208      * the children of first level, then search in the 2nd level of the first
209      * children, ...
210      *
211      * @param parent
212      * parent node
213      * @param nodeName
214      * node name
215      * @param recursive
216      * boolean to know if we got through the xml tree
217      * @return a node list of nodes with this name
218      */

219     public static NodeList JavaDoc findChildren(Node JavaDoc parent, String JavaDoc nodeName,
220             boolean recursive) {
221         parent.normalize();
222         NodeSet nodeList = new NodeSet();
223         if (parent != null && nodeName != null) {
224             NodeList JavaDoc nl = parent.getChildNodes();
225             for (int i = 0; i < nl.getLength(); i++) {
226                 if (nodeName.equals(nl.item(i).getNodeName())) {
227                     nodeList.addElement(nl.item(i));
228                 }
229             }
230             // now, search recursively if required
231
if (recursive) {
232                 for (int i = 0; i < nl.getLength(); i++) {
233                     nodeList = findChildren(nl.item(i), nodeName, nodeList);
234                 }
235             }
236         }
237         return nodeList;
238     }
239
240     /**
241      * Return the value of the attribute in the node
242      *
243      * @param n
244      * the node
245      * @param attName
246      * the name of the attribute
247      * @return the value of the attribute, null if not found
248      */

249     public static String JavaDoc getAttributeValue(Node JavaDoc n, String JavaDoc attName) {
250         NamedNodeMap JavaDoc atts = n.getAttributes();
251         Node JavaDoc att = atts.getNamedItem(attName);
252         if (att != null) {
253             return att.getNodeValue();
254         }
255         return null;
256     }
257
258     /**
259      * Return the first child of a node, regardless <i>text</i> node
260      *
261      * @param node
262      * @return
263      */

264     public static Node JavaDoc getFirstChild(Node JavaDoc node) {
265         node.normalize();
266         Node JavaDoc result = node.getFirstChild();
267         while (result != null && result.getNodeType() == Node.TEXT_NODE) {
268             result = result.getNextSibling();
269         }
270         return result;
271     }
272
273     /**
274      * Return the next sibling of a node, regardless <i>text</i> node
275      *
276      * @param node
277      * @return
278      */

279     public static Node JavaDoc getNextSibling(Node JavaDoc node) {
280         node.normalize();
281         Node JavaDoc result = node.getNextSibling();
282         while (result != null && result.getNodeType() == Node.TEXT_NODE) {
283             result = result.getNextSibling();
284         }
285         return result;
286     }
287
288     /**
289      * Search a document to see if a namespace is declared in it and if it is
290      * returns this namespace URI
291      *
292      * @param node
293      * The node for which we will lookup the prefix
294      * @param namespaceURI
295      * The URI for which we lookup the prefix
296      * @param deep
297      * false if we want to search all the document
298      * @return the prefix if the namespace was found, else null
299      */

300     public static String JavaDoc getPrefixForNamespaceURI(Node JavaDoc node,
301             String JavaDoc namespaceURI, boolean deep) {
302         String JavaDoc result = "";
303         if (!deep) {
304             if (namespaceURI != null && !"".equals(namespaceURI)) {
305                 while (node.getParentNode() != null) {
306                     node = node.getParentNode();
307                 }
308                 // Search in root node attributes
309
NamedNodeMap JavaDoc attributes = node.getAttributes();
310                 int i = 0;
311                 if (attributes != null) {
312                     while (i < attributes.getLength()) {
313                         Node JavaDoc attr = attributes.item(i++);
314                         if (namespaceURI.equals(attr.getNodeValue())) {
315                             String JavaDoc nodeName = attr.getNodeName();
316                             if (nodeName.startsWith("xmlns:")) {
317                                 result = nodeName.replaceFirst("xmlns:", "")
318                                         + ":";
319                                 return result;
320                             } else if (nodeName.startsWith("xmlns")) {
321                                 return result;
322                             }
323                         }
324                     }
325                 }
326                 // Search in child nodes attributes
327
i = 0;
328                 NodeList JavaDoc nl = node.getChildNodes();
329                 while (i < nl.getLength()) {
330                     Node JavaDoc tmpNode = nl.item(i++);
331                     String JavaDoc prefix = getPrefixForNamespaceURI(tmpNode,
332                             namespaceURI, true);
333                     if (prefix != null) {
334                         return prefix;
335                     }
336                 }
337             }
338         } else {
339             // Search in root node attributes
340
NamedNodeMap JavaDoc attributes = node.getAttributes();
341             int i = 0;
342             if (attributes != null) {
343                 while (i < attributes.getLength()) {
344                     Node JavaDoc attr = attributes.item(i++);
345                     if (namespaceURI.equals(attr.getNodeValue())) {
346                         String JavaDoc nodeName = attr.getNodeName();
347                         if (nodeName.startsWith("xmlns:")) {
348                             result = nodeName.replaceFirst("xmlns:", "") + ":";
349                             return result;
350                         } else if (nodeName.startsWith("xmlns")) {
351                             return result;
352                         }
353                     }
354                 }
355             }
356             // Search in child nodes attributes
357
i = 0;
358             NodeList JavaDoc nl = node.getChildNodes();
359             while (i < nl.getLength()) {
360                 Node JavaDoc tmpNode = nl.item(i++);
361                 String JavaDoc prefix = getPrefixForNamespaceURI(tmpNode, namespaceURI,
362                         true);
363                 if (prefix != null) {
364                     return prefix;
365                 }
366             }
367             return null;
368         }
369         return result;
370     }
371
372     /**
373      * Search a document to see if a prefix is declared in it and if it is
374      * returns its namespace URI
375      *
376      * @param node
377      * The node for which we will lookup the Uri
378      * @param pref
379      * The prefix for which we lookup the Uri
380      * @param deep
381      * false if we want to search all the document
382      * @return the Uri if the prefix was found, else null
383      */

384     public static String JavaDoc getNamespaceURIForPrefix(Node JavaDoc node, String JavaDoc pref,
385             boolean deep) {
386         String JavaDoc result = "";
387         if (!deep) {
388             if (pref != null && !"".equals(pref)) {
389                 while (node.getParentNode() != null) {
390                     node = node.getParentNode();
391                 }
392                 // Search in root node attributes
393
NamedNodeMap JavaDoc attributes = node.getAttributes();
394                 int i = 0;
395                 if (attributes != null) {
396                     while (i < attributes.getLength()) {
397                         Node JavaDoc attr = attributes.item(i++);
398                         if (attr.getNodeName().startsWith("xmlns:" + pref)) {
399                             result = attr.getNodeValue();
400                             return result;
401                         }
402                     }
403                 }
404                 // Search in child nodes attributes
405
i = 0;
406                 NodeList JavaDoc nl = node.getChildNodes();
407                 while (i < nl.getLength()) {
408                     Node JavaDoc tmpNode = nl.item(i++);
409                     String JavaDoc uri = getNamespaceURIForPrefix(tmpNode, pref, true);
410                     if (uri != null) {
411                         return uri;
412                     }
413                 }
414             }
415         } else {
416             // Search in root node attributes
417
NamedNodeMap JavaDoc attributes = node.getAttributes();
418             int i = 0;
419             if (attributes != null) {
420                 while (i < attributes.getLength()) {
421                     Node JavaDoc attr = attributes.item(i++);
422                     if (attr.getNodeName().startsWith("xmlns:" + pref)) {
423                         result = attr.getNodeValue();
424                         return result;
425                     }
426                 }
427             }
428             // Search in child nodes attributes
429
i = 0;
430             NodeList JavaDoc nl = node.getChildNodes();
431             while (i < nl.getLength()) {
432                 Node JavaDoc tmpNode = nl.item(i++);
433                 String JavaDoc uri = getNamespaceURIForPrefix(tmpNode, pref, true);
434                 if (uri != null) {
435                     return uri;
436                 }
437             }
438             return null;
439         }
440         return result;
441     }
442
443     /**
444      * Return the <i>text</i> element of a node
445      *
446      * @param node
447      * @return
448      */

449     public static String JavaDoc getTextContent(Node JavaDoc node) {
450         node.normalize();
451         NodeList JavaDoc list = node.getChildNodes();
452         for (int i = 0; i < list.getLength(); i++) {
453             if (list.item(i).getNodeType() == Node.TEXT_NODE) {
454                 return list.item(i).getNodeValue();
455             }
456         }
457         return null;
458     }
459
460     /**
461      * Transform an XML {@link Node} into a String
462      *
463      * @param node
464      * the XML {@link Node} to parse
465      * @return the resulting String, null if node is null
466      * @throws TransformerException
467      * if errors occured during transformation
468      */

469     public static String JavaDoc parseToString(Node JavaDoc node) throws TransformerException JavaDoc {
470         String JavaDoc result = null;
471         if (node != null) {
472             node.normalize();
473             Transformer JavaDoc transformer = TransformerFactory.newInstance()
474                     .newTransformer();
475             StringWriter JavaDoc stringWriter = new StringWriter JavaDoc(128);
476             transformer.transform(new DOMSource JavaDoc(node), new StreamResult JavaDoc(
477                     stringWriter));
478             StringBuffer JavaDoc buffer = stringWriter.getBuffer();
479             result = buffer.toString();
480         }
481         return result;
482     }
483
484     /**
485      * Search recursively for children with the given nodeName.
486      *
487      * @param parent
488      * parent node
489      * @param nodeName
490      * node name
491      * @param nodeList
492      * Set of nodes to be completed
493      * @return a node list of nodes with this name
494      */

495     private static NodeSet findChildren(Node JavaDoc parent, String JavaDoc nodeName,
496             NodeSet nodeList) {
497         if (parent != null && nodeName != null) {
498             NodeList JavaDoc nl = parent.getChildNodes();
499             for (int i = 0; i < nl.getLength(); i++) {
500                 if (nodeName.equals(nl.item(i).getNodeName())) {
501                     nodeList.addElement(nl.item(i));
502                 }
503             }
504             for (int i = 0; i < nl.getLength(); i++) {
505                 nodeList = findChildren(nl.item(i), nodeName, nodeList);
506             }
507         }
508         return nodeList;
509     }
510
511 }
512
Popular Tags