1 11 package org.eclipse.pde.internal.build; 12 13 import java.io.*; 14 import java.util.*; 15 16 19 public class XMLWriter extends PrintWriter { 20 protected int tab; 21 22 23 protected static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; 25 public XMLWriter(OutputStream output) throws UnsupportedEncodingException { 26 super(new OutputStreamWriter(output, "UTF8")); tab = 0; 28 println(XML_VERSION); 29 } 30 31 public void endTag(String name) { 32 tab--; 33 printTag('/' + name, null); 34 } 35 36 public void printSimpleTag(String name, Object value) { 37 if (value == null) 38 return; 39 printTag(name, null, true, false, false); 40 print(getEscaped(String.valueOf(value))); 41 printTag('/' + name, null, false, true, false); 42 } 43 44 public void printTabulation() { 45 for (int i = 0; i < tab; i++) 46 super.print('\t'); 47 } 48 49 public void printTag(String name, Map parameters) { 50 printTag(name, parameters, true, true, false); 51 } 52 53 public void printTag(String name, Map parameters, boolean shouldTab, boolean newLine, boolean close) { 54 StringBuffer sb = new StringBuffer (); 55 sb.append("<"); sb.append(name); 57 if (parameters != null) 58 for (Enumeration enumeration = Collections.enumeration(parameters.keySet()); enumeration.hasMoreElements();) { 59 sb.append(" "); String key = (String ) enumeration.nextElement(); 61 if (parameters.get(key) != null) { 62 sb.append(key); 63 sb.append("=\""); sb.append(getEscaped(String.valueOf(parameters.get(key)))); 65 sb.append("\""); } 67 } 68 if (close) 69 sb.append("/>"); else 71 sb.append(">"); if (shouldTab) 73 printTabulation(); 74 if (newLine) 75 println(sb.toString()); 76 else 77 print(sb.toString()); 78 } 79 80 public void startTag(String name, Map parameters) { 81 startTag(name, parameters, true); 82 } 83 84 public void startTag(String name, Map parameters, boolean newLine) { 85 printTag(name, parameters, true, newLine, false); 86 tab++; 87 } 88 89 private static void appendEscapedChar(StringBuffer buffer, char c) { 90 buffer.append(getReplacement(c)); 91 } 92 93 public static String getEscaped(String s) { 94 StringBuffer result = new StringBuffer (s.length() + 10); 95 for (int i = 0; i < s.length(); ++i) 96 appendEscapedChar(result, s.charAt(i)); 97 return result.toString(); 98 } 99 100 private static String getReplacement(char c) { 101 switch (c) { 104 case '<' : 105 return "<"; case '>' : 107 return ">"; case '"' : 109 return """; case '\'' : 111 return "'"; case '&' : 113 return "&"; default : 115 return String.valueOf(c); 116 } 117 } 118 119 public void printlnEscaped(String s) { 120 if (s != null) 121 println(getEscaped(s)); 122 else 123 println(); 124 } 125 } 126 | Popular Tags |