1 11 package org.eclipse.core.internal.resources; 12 13 import java.io.*; 14 import java.util.HashMap ; 15 import java.util.Iterator ; 16 17 20 public class XMLWriter extends PrintWriter { 21 protected int tab; 22 23 24 protected static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; 26 public XMLWriter(OutputStream output) throws UnsupportedEncodingException { 27 super(new OutputStreamWriter(output, "UTF8")); tab = 0; 29 println(XML_VERSION); 30 } 31 32 public void endTag(String name) { 33 tab--; 34 printTag('/' + name, null); 35 } 36 37 public void printSimpleTag(String name, Object value) { 38 if (value != null) { 39 printTag(name, null, true, false); 40 print(getEscaped(String.valueOf(value))); 41 printTag('/' + name, null, false, true); 42 } 43 } 44 45 public void printTabulation() { 46 for (int i = 0; i < tab; i++) 47 super.print('\t'); 48 } 49 50 public void printTag(String name, HashMap parameters) { 51 printTag(name, parameters, true, true); 52 } 53 54 public void printTag(String name, HashMap parameters, boolean shouldTab, boolean newLine) { 55 StringBuffer sb = new StringBuffer (); 56 sb.append("<"); sb.append(name); 58 if (parameters != null) 59 for (Iterator it = parameters.keySet().iterator(); it.hasNext();) { 60 sb.append(" "); String key = (String ) it.next(); 62 sb.append(key); 63 sb.append("=\""); sb.append(getEscaped(String.valueOf(parameters.get(key)))); 65 sb.append("\""); } 67 sb.append(">"); if (shouldTab) 69 printTabulation(); 70 if (newLine) 71 println(sb.toString()); 72 else 73 print(sb.toString()); 74 } 75 76 public void startTag(String name, HashMap parameters) { 77 startTag(name, parameters, true); 78 } 79 80 public void startTag(String name, HashMap parameters, boolean newLine) { 81 printTag(name, parameters, true, newLine); 82 tab++; 83 } 84 85 private static void appendEscapedChar(StringBuffer buffer, char c) { 86 String replacement = getReplacement(c); 87 if (replacement != null) { 88 buffer.append('&'); 89 buffer.append(replacement); 90 buffer.append(';'); 91 } else { 92 buffer.append(c); 93 } 94 } 95 96 public static String getEscaped(String s) { 97 StringBuffer result = new StringBuffer (s.length() + 10); 98 for (int i = 0; i < s.length(); ++i) 99 appendEscapedChar(result, s.charAt(i)); 100 return result.toString(); 101 } 102 103 private static String getReplacement(char c) { 104 switch (c) { 107 case '<' : 108 return "lt"; case '>' : 110 return "gt"; case '"' : 112 return "quot"; case '\'' : 114 return "apos"; case '&' : 116 return "amp"; } 118 return null; 119 } 120 } 121 | Popular Tags |