1 11 package org.eclipse.team.internal.ccvs.ui; 12 13 import java.io.*; 14 import java.util.Collections ; 15 import java.util.Enumeration ; 16 import java.util.HashMap ; 17 18 21 public class XMLWriter extends PrintWriter { 22 protected int tab; 23 24 25 protected static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; 27 public XMLWriter(OutputStream output) throws UnsupportedEncodingException { 28 super(new OutputStreamWriter(output, "UTF8")); tab = 0; 30 println(XML_VERSION); 31 } 32 public void endTag(String name) { 33 tab--; 34 printTag('/' + name, null); 35 } 36 public void printSimpleTag(String name, Object value) { 37 if (value != null) { 38 printTag(name, null, true, false); 39 print(getEscaped(String.valueOf(value))); 40 printTag('/' + name, null, false, true); 41 } 42 } 43 public void printTabulation() { 44 for (int i = 0; i < tab; i++) 45 super.print('\t'); 46 } 47 private void printTag(String name, HashMap parameters) { 48 printTag(name, parameters, true, true); 49 } 50 private void printTag(String name, HashMap parameters, boolean tab, boolean newLine) { 51 printTag(name, parameters, tab, newLine, false); 52 } 53 private void printTag(String name, HashMap parameters, boolean tab, boolean newLine, boolean end) { 54 StringBuffer sb = new StringBuffer (); 55 sb.append("<"); sb.append(name); 57 if (parameters != null) 58 for (Enumeration e = Collections.enumeration(parameters.keySet()); e.hasMoreElements();) { 59 sb.append(" "); String key = (String ) e.nextElement(); 61 sb.append(key); 62 sb.append("=\""); sb.append(getEscaped(String.valueOf(parameters.get(key)))); 64 sb.append("\""); } 66 if (end) 67 sb.append('/'); 68 sb.append(">"); if (tab) 70 printTabulation(); 71 if (newLine) 72 println(sb.toString()); 73 else 74 print(sb.toString()); 75 } 76 public void startTag(String name, HashMap parameters) { 77 startTag(name, parameters, true); 78 } 79 public void startTag(String name, HashMap parameters, boolean newLine) { 80 printTag(name, parameters, true, newLine); 81 tab++; 82 } 83 public void startAndEndTag(String name, HashMap parameters, boolean newLine) { 84 printTag(name, parameters, true, true, true); 85 } 86 private static void appendEscapedChar(StringBuffer buffer, char c) { 87 String replacement = getReplacement(c); 88 if (replacement != null) { 89 buffer.append('&'); 90 buffer.append(replacement); 91 buffer.append(';'); 92 } else { 93 buffer.append(c); 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 private static String getReplacement(char c) { 103 switch (c) { 106 case '<' : 107 return "lt"; case '>' : 109 return "gt"; case '"' : 111 return "quot"; case '\'' : 113 return "apos"; case '&' : 115 return "amp"; } 117 return null; 118 } 119 } 120 | Popular Tags |