KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dom > treewalker > TestFirstChild


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001 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 "Xerces" 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 developed by Christian Geuer-Pollmann. For more
53  * information on the Apache Software Foundation, please see
54  * <http://www.apache.org/>.
55  */

56
57 package dom.treewalker;
58 import java.io.ByteArrayOutputStream JavaDoc;
59 import java.io.OutputStreamWriter JavaDoc;
60 import java.io.PrintWriter JavaDoc;
61
62 import javax.xml.parsers.DocumentBuilder JavaDoc;
63 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
64 import javax.xml.parsers.ParserConfigurationException JavaDoc;
65
66 import org.w3c.dom.Document JavaDoc;
67 import org.w3c.dom.Element JavaDoc;
68 import org.w3c.dom.Node JavaDoc;
69 import org.w3c.dom.Text JavaDoc;
70 import org.w3c.dom.traversal.DocumentTraversal;
71 import org.w3c.dom.traversal.NodeFilter;
72 import org.w3c.dom.traversal.TreeWalker;
73
74
75 /**
76  * The class tests TreeWalkerImpl.firstChild() and TreeWalkerImpl.nextSibling();
77  * The class generates simple XML document and traverses it.
78  *
79  * @author Christian Geuer-Pollmann <geuer-pollmann@nue.et-inf.uni-siegen.de>
80  * @version $Id: TestFirstChild.java,v 1.2 2005/01/26 08:28:45 jkjome Exp $
81  */

82 public class TestFirstChild {
83
84     public static void main(String JavaDoc args[]) throws Exception JavaDoc {
85
86
87         System.out.println(" --- "
88                            + org.enhydra.apache.xerces.framework.Version.fVersion
89                            + " --- ");
90         Document JavaDoc doc = getNodeSet1();
91         NodeFilter nodefilter = null;
92         boolean entityReferenceExpansion = true;
93         int whatToShow = NodeFilter.SHOW_ALL;
94         TreeWalker treewalker =
95         ((DocumentTraversal) doc).createTreeWalker(doc, whatToShow,
96                                                    nodefilter, entityReferenceExpansion);
97         ByteArrayOutputStream JavaDoc bytearrayoutputstream =
98         new ByteArrayOutputStream JavaDoc();
99         PrintWriter JavaDoc printwriter =
100         new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(bytearrayoutputstream,
101                                                "UTF8"));
102
103         process2(treewalker, printwriter);
104         printwriter.flush();
105
106         System.out.println();
107         System.out.println("Testing the following XML document:\n" + new String JavaDoc(bytearrayoutputstream.toByteArray()));
108     }
109
110     /**
111      * Method getNodeSet1
112      *
113      * @return
114      * @throws ParserConfigurationException
115      */

116     private static Document JavaDoc getNodeSet1()
117     throws ParserConfigurationException JavaDoc {
118
119         DocumentBuilderFactory JavaDoc dfactory =
120         DocumentBuilderFactory.newInstance();
121
122         dfactory.setValidating(false);
123         dfactory.setNamespaceAware(true);
124
125         DocumentBuilder JavaDoc db = dfactory.newDocumentBuilder();
126         Document JavaDoc doc = db.newDocument();
127         Element JavaDoc root = doc.createElement("RootElement");
128         Element JavaDoc e1 = doc.createElement("Element1");
129         Element JavaDoc e2 = doc.createElement("Element2");
130         Element JavaDoc e3 = doc.createElement("Element3");
131         Text JavaDoc e3t = doc.createTextNode("Text in Element3");
132
133         e3.appendChild(e3t);
134         root.appendChild(e1);
135         root.appendChild(e2);
136         root.appendChild(e3);
137         doc.appendChild(root);
138
139         String JavaDoc s1 ="<RootElement><Element1/><Element2/><Element3>Text in Element3</Element3></RootElement>";
140
141         return doc;
142     }
143
144     /**
145      * recursively traverses the tree
146      *
147      * for simplicity, I don't handle comments, Attributes, PIs etc.
148      * Only Text, Document and Element
149      *
150      * @param treewalker
151      * @param printwriter
152      */

153     private static void process2(TreeWalker treewalker,
154                                  PrintWriter JavaDoc printwriter) {
155
156         Node JavaDoc currentNode = treewalker.getCurrentNode();
157
158         switch (currentNode.getNodeType()) {
159         
160         case Node.TEXT_NODE :
161         case Node.CDATA_SECTION_NODE :
162             printwriter.print(currentNode.getNodeValue());
163             break;
164
165         case Node.ENTITY_REFERENCE_NODE :
166         case Node.DOCUMENT_NODE :
167         case Node.ELEMENT_NODE :
168         default :
169             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
170                 printwriter.print('<');
171                 printwriter.print(currentNode.getNodeName());
172                 printwriter.print(">");
173             }
174
175             Node JavaDoc node1 = treewalker.firstChild();
176
177             if (node1 == null) {
178                 System.out.println(getNodeTypeString(currentNode.getNodeType())
179                                    + "_NODE parent: "
180                                    + currentNode.getNodeName()
181                                    + " has no children ");
182             }
183             else {
184                 System.out.println(getNodeTypeString(currentNode.getNodeType())
185                                    + "_NODE parent: "
186                                    + currentNode.getNodeName()
187                                    + " has children ");
188
189                 while (node1 != null) {
190                     {
191                         String JavaDoc qStr = "";
192
193                         for (Node JavaDoc q = node1; q != null; q = q.getParentNode()) {
194                             qStr = q.getNodeName() + "/" + qStr;
195                         }
196
197                         System.out.println(getNodeTypeString(currentNode.getNodeType())
198                                            + "_NODE process child " + qStr);
199                     }
200
201
202                     // recursion !!!
203
process2(treewalker, printwriter);
204
205                     node1 = treewalker.nextSibling();
206                     if (node1 != null) {
207                         System.out.println("treewalker.nextSibling() = "
208                                            + node1.getNodeName());
209                     }
210                 } // while(node1 != null)
211
}
212
213             System.out.println("setCurrentNode() back to "
214                                + currentNode.getNodeName());
215             treewalker.setCurrentNode(currentNode);
216
217             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
218                 printwriter.print("</");
219                 printwriter.print(currentNode.getNodeName());
220                 printwriter.print(">");
221             }
222
223             break;
224         }
225     }
226
227     /** Field nodeTypeString */
228     private static String JavaDoc[] nodeTypeString = new String JavaDoc[]{ "", "ELEMENT",
229         "ATTRIBUTE",
230         "TEXT_NODE",
231         "CDATA_SECTION",
232         "ENTITY_REFERENCE",
233         "ENTITY",
234         "PROCESSING_INSTRUCTION",
235         "COMMENT",
236         "DOCUMENT",
237         "DOCUMENT_TYPE",
238         "DOCUMENT_FRAGMENT",
239         "NOTATION"};
240
241
242
243     /**
244      *
245      * Transforms <code>org.w3c.dom.Node.XXX_NODE</code> NodeType values into
246      * XXX Strings.
247      *
248      * @param nodeType as taken from the {@link org.w3c.dom.Node#getNodeType}
249      * function
250      * @return the String value.
251      * @see org.w3c.dom.Node#getNodeType
252      * @param nodeType
253      * @return
254      */

255     public static String JavaDoc getNodeTypeString(short nodeType) {
256
257         if ((nodeType > 0) && (nodeType < 13)) {
258             return nodeTypeString[nodeType];
259         }
260         else {
261             return "";
262         }
263     }
264
265 }
266
Popular Tags