KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > nu > xom > samples > TextMerger


1 /* Copyright 2004 Elliotte Rusty Harold
2    
3    This library is free software; you can redistribute it and/or modify
4    it under the terms of version 2.1 of the GNU Lesser General Public
5    License as published by the Free Software Foundation.
6    
7    This library is distributed in the hope that it will be useful,
8    but WITHOUT ANY WARRANTY; without even the implied warranty of
9    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10    GNU Lesser General Public License for more details.
11    
12    You should have received a copy of the GNU Lesser General Public
13    License along with this library; if not, write to the
14    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
15    Boston, MA 02111-1307 USA
16    
17    You can contact Elliotte Rusty Harold by sending e-mail to
18    elharo@metalab.unc.edu. Please include the word "XOM" in the
19    subject line. The XOM home page is located at http://www.xom.nu/
20 */

21
22 package nu.xom.samples;
23
24 import nu.xom.Element;
25 import nu.xom.Node;
26 import nu.xom.ParentNode;
27 import nu.xom.Text;
28
29 /**
30  * <p>
31  * Utility methods for merging all consecutive text nodes.
32  * </p>
33  *
34  * @author Elliotte Rusty Harold
35  * @version 1.0
36  *
37  */

38 public class TextMerger {
39
40     
41     public static void merge(ParentNode parent) {
42         
43         for (int i = 0; i < parent.getChildCount(); i++) {
44             Node child = parent.getChild(i);
45             if (child instanceof Text) {
46                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc(child.getValue());
47                 Node nextChild;
48                 while ((nextChild = parent.getChild(i+1)) instanceof Text) {
49                     sb.append(nextChild.getValue());
50                     parent.removeChild(nextChild);
51                     if (i+1 == parent.getChildCount()) break;
52                 }
53                 if (sb.length() == 0) parent.removeChild(child);
54                 else parent.replaceChild(child, new Text(sb.toString()));
55             }
56             else if (child instanceof Element) {
57                 merge((ParentNode) child);
58             }
59         }
60         
61     }
62     
63 }
64
Popular Tags