1 28 29 package net.n3.nanoxml; 30 31 import java.io.Reader ; 32 import java.util.Stack ; 33 34 43 public class StdXMLBuilder implements IXMLBuilder 44 { 45 46 49 private Stack stack; 50 51 54 private XMLElement root; 55 56 59 public StdXMLBuilder() 60 { 61 this.stack = null; 62 this.root = null; 63 } 64 65 68 protected void finalize() throws Throwable 69 { 70 this.root = null; 71 this.stack.clear(); 72 this.stack = null; 73 super.finalize(); 74 } 75 76 82 public void startBuilding(String systemID, int lineNr) 83 { 84 this.stack = new Stack (); 85 this.root = null; 86 } 87 88 95 public void newProcessingInstruction(String target, Reader reader) 96 { 97 } 99 100 111 public void startElement(String name, String nsPrefix, String nsSystemID, String systemID, 112 int lineNr) 113 { 114 XMLElement elt = new XMLElement(name, systemID, lineNr); 115 116 if (this.stack.empty()) 117 { 118 this.root = elt; 119 } 120 else 121 { 122 XMLElement top = (XMLElement) this.stack.peek(); 123 top.addChild(elt); 124 } 125 126 this.stack.push(elt); 127 } 128 129 139 public void elementAttributesProcessed(String name, String nsPrefix, String nsSystemID) 140 { 141 } 143 144 153 public void endElement(String name, String nsPrefix, String nsSystemID) 154 { 155 XMLElement elt = (XMLElement) this.stack.pop(); 156 157 if (elt.getChildrenCount() == 1) 158 { 159 XMLElement child = elt.getChildAtIndex(0); 160 161 if (child.getName() == null) 162 { 163 elt.setContent(child.getContent()); 164 elt.removeChildAtIndex(0); 165 } 166 } 167 } 168 169 180 public void addAttribute(String key, String nsPrefix, String nsSystemID, String value, 181 String type) throws Exception 182 { 183 XMLElement top = (XMLElement) this.stack.peek(); 184 185 if (top.hasAttribute(key)) { throw new XMLParseException(top.getSystemID(), 186 top.getLineNr(), "Duplicate attribute: " + key); } 187 188 top.setAttribute(key, value); 189 } 190 191 203 public void addPCData(Reader reader, String systemID, int lineNr) throws Exception 204 { 205 int bufSize = 2048; 206 int sizeRead = 0; 207 StringBuffer str = new StringBuffer (bufSize); 208 char[] buf = new char[bufSize]; 209 210 for (;;) 211 { 212 if (sizeRead >= bufSize) 213 { 214 bufSize *= 2; 215 str.ensureCapacity(bufSize); 216 } 217 218 int size = reader.read(buf); 219 220 if (size < 0) 221 { 222 break; 223 } 224 225 str.append(buf, 0, size); 226 sizeRead += size; 227 } 228 229 XMLElement elt = new XMLElement(null, systemID, lineNr); 230 elt.setContent(str.toString()); 231 232 if (!this.stack.empty()) 233 { 234 XMLElement top = (XMLElement) this.stack.peek(); 235 top.addChild(elt); 236 } 237 } 238 239 247 public Object getResult() 248 { 249 return this.root; 250 } 251 252 } 253 | Popular Tags |