1 /*******************************************************************************
2 * Copyright (c) 2000, 2004 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.internal.core;
13 import java.io.PrintWriter;
14 import java.io.Writer;
15 import java.util.Collections;
16 import java.util.Enumeration;
17 import java.util.HashMap;
22 class XMLWriter extends PrintWriter {
24 private static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
26 private static void appendEscapedChar(StringBuffer buffer, char c) {
27 String replacement = getReplacement(c);
28 if (replacement != null) {
30 buffer.append(replacement);
37 private static String getEscaped(String s) {
38 StringBuffer result = new StringBuffer(s.length() + 10);
39 for (int i = 0; i < s.length(); ++i)
40 appendEscapedChar(result, s.charAt(i));
41 return result.toString();
44 private static String getReplacement(char c) {
45 // Encode special XML characters into the equivalent character
47 // These five are defined by default for all XML documents.
50 return "lt"; //$NON-NLS-1$
52 return "gt"; //$NON-NLS-1$
54 return "quot"; //$NON-NLS-1$
56 return "apos"; //$NON-NLS-1$
58 return "amp"; //$NON-NLS-1$
65 public XMLWriter(Writer writer) {
71 public void endTag(String name, boolean insertTab) {
73 printTag('/' + name, null, insertTab, true, false);
76 private void printTabulation() {
77 for (int i = 0; i < tab; i++)
81 public void printTag(String name, HashMap parameters, boolean insertTab,
82 boolean insertNewLine, boolean closeTag) {
83 StringBuffer sb = new StringBuffer();
84 sb.append("<"); //$NON-NLS-1$
86 if (parameters != null) {
87 for (Enumeration en = Collections.enumeration(parameters.keySet()); en
88 .hasMoreElements();) {
89 sb.append(" "); //$NON-NLS-1$
90 String key = (String) en.nextElement();
92 sb.append("=\""); //$NON-NLS-1$
93 sb.append(getEscaped(String.valueOf(parameters.get(key))));
94 sb.append("\""); //$NON-NLS-1$
98 sb.append("/>"); //$NON-NLS-1$
100 sb.append(">"); //$NON-NLS-1$
106 println(sb.toString());
108 print(sb.toString());
112 public void startTag(String name, boolean insertTab) {
113 printTag(name, null, insertTab, true, false);