source: josm/trunk/src/org/openstreetmap/josm/io/XmlWriter.java@ 5299

Last change on this file since 5299 was 5146, checked in by bastiK, 12 years ago

fixed #7558 - History window shows XML entities in user names

  • Property svn:eol-style set to native
File size: 2.1 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.io;
3
4import java.io.PrintWriter;
5import java.util.HashMap;
6
7/**
8 * Helper class to use for xml outputting classes.
9 *
10 * @author imi
11 */
12public class XmlWriter {
13
14 protected PrintWriter out;
15
16 public XmlWriter(PrintWriter out) {
17 this.out = out;
18 }
19
20 public void flush() {
21 out.flush();
22 }
23
24 public static String encode(String unencoded) {
25 return encode(unencoded, false);
26 }
27
28 /**
29 * Encode the given string in XML1.0 format.
30 * Optimized to fast pass strings that don't need encoding (normal case).
31 *
32 * @param unencoded the unencoded input string
33 * @param keepApos true if apostrophe sign should stay as it is (in order to work around
34 * a Java bug that renders
35 * new JLabel("<html>&apos;</html>")
36 * literally as 6 character string, see #7558)
37 */
38 public static String encode(String unencoded, boolean keepApos) {
39 StringBuilder buffer = null;
40 for (int i = 0; i < unencoded.length(); ++i) {
41 String encS = null;
42 if (!keepApos || unencoded.charAt(i) != '\'') {
43 encS = XmlWriter.encoding.get(unencoded.charAt(i));
44 }
45 if (encS != null) {
46 if (buffer == null) {
47 buffer = new StringBuilder(unencoded.substring(0,i));
48 }
49 buffer.append(encS);
50 } else if (buffer != null) {
51 buffer.append(unencoded.charAt(i));
52 }
53 }
54 return (buffer == null) ? unencoded : buffer.toString();
55 }
56
57 /**
58 * The output writer to save the values to.
59 */
60 final private static HashMap<Character, String> encoding = new HashMap<Character, String>();
61 static {
62 encoding.put('<', "&lt;");
63 encoding.put('>', "&gt;");
64 encoding.put('"', "&quot;");
65 encoding.put('\'', "&apos;");
66 encoding.put('&', "&amp;");
67 encoding.put('\n', "&#xA;");
68 encoding.put('\r', "&#xD;");
69 encoding.put('\t', "&#x9;");
70 }
71}
Note: See TracBrowser for help on using the repository browser.