1 3 package org.jgroups.util; 4 5 6 14 16 import org.w3c.dom.*; 17 18 import java.io.PrintWriter ; 19 20 21 22 23 public class PrintXMLTree { 24 25 public PrintXMLTree() { 26 } 27 28 29 public static void print(PrintWriter out, 30 Element root) { 31 32 print("", out, root); 33 } 34 35 protected static void print(String prepend, 36 PrintWriter out, 37 Element root) { 38 39 String attributeName=null; 41 if(root == null) return; 42 43 print(prepend, out, root, root.getAttributes()); 44 45 NodeList elements=root.getChildNodes(); 46 47 if(elements == null) return; 49 50 if(attributeName == null) { 52 int elementCount=elements.getLength(); 53 for(int i=0; i < elementCount; i++) { 54 if(elements.item(i).getNodeType() == Node.ELEMENT_NODE) { 55 Element element=(Element)elements.item(i); 56 print(prepend, out, element, element.getAttributes()); 57 } 58 } 59 } 60 61 else { 63 int elementCount=elements.getLength(); 64 for(int i=0; i < elementCount; i++) { 65 Element element=(Element)elements.item(i); 66 NamedNodeMap attributes=element.getAttributes(); 67 if(attributes.getNamedItem(attributeName) != null) { 68 print(prepend, out, element, attributes); 69 } 70 } 71 } 72 73 } 75 76 77 protected static void print(String prepend, 78 PrintWriter out, 79 Element element, 80 NamedNodeMap attributes) { 81 82 out.print(prepend); 83 out.print('<'); 84 out.print(element.getNodeName()); 85 86 if(attributes != null) { 87 int attributeCount=attributes.getLength(); 88 for(int i=0; i < attributeCount; i++) { 89 Attr attribute=(Attr)attributes.item(i); 90 out.print(' '); 91 out.print(attribute.getNodeName()); 92 out.print("=\""); 93 out.print(normalize(attribute.getNodeValue())); 94 out.print('"'); 95 } 96 } 97 out.println('>'); 98 99 100 NodeList list=element.getChildNodes(); 101 102 for(int i=0; i < list.getLength(); i++) { 103 if(list.item(i).getNodeType() == Node.ELEMENT_NODE) 104 print(prepend + " ", out, (Element)list.item(i)); 105 else 106 if(list.item(i).getNodeType() == Node.TEXT_NODE && 107 list.item(i).getNodeValue().trim().length() > 0) 108 out.println(prepend + " " + list.item(i).getNodeValue()); 109 } 110 111 out.print(prepend + "</"); 112 out.print(element.getNodeName()); 113 out.println(">"); 114 115 out.flush(); 116 117 } 119 public static String normalize(String s) { 120 StringBuffer str=new StringBuffer (); 121 122 int len=(s != null)? s.length() : 0; 123 for(int i=0; i < len; i++) { 124 char ch=s.charAt(i); 125 switch(ch) { 126 case '<': 127 { 128 str.append("<"); 129 break; 130 } 131 case '>': 132 { 133 str.append(">"); 134 break; 135 } 136 case '&': 137 { 138 str.append("&"); 139 break; 140 } 141 case '"': 142 { 143 str.append("""); 144 break; 145 } 146 case '\r': 147 case '\n': 148 { 149 str.append("&#"); 150 str.append(Integer.toString(ch)); 151 str.append(';'); 152 break; 153 } 154 default: 155 { 156 str.append(ch); 157 } 158 } 159 } 160 161 return str.toString(); 162 163 } } 165 | Popular Tags |