1 | // License: GPL. Copyright 2007 by Immanuel Scholz and others
|
---|
2 | package org.openstreetmap.josm.io;
|
---|
3 |
|
---|
4 | import java.io.PrintWriter;
|
---|
5 | import java.util.HashMap;
|
---|
6 |
|
---|
7 | /**
|
---|
8 | * Helper class to use for xml outputting classes.
|
---|
9 | *
|
---|
10 | * @author imi
|
---|
11 | */
|
---|
12 | public 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>'</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('<', "<");
|
---|
63 | encoding.put('>', ">");
|
---|
64 | encoding.put('"', """);
|
---|
65 | encoding.put('\'', "'");
|
---|
66 | encoding.put('&', "&");
|
---|
67 | encoding.put('\n', "
");
|
---|
68 | encoding.put('\r', "
");
|
---|
69 | encoding.put('\t', "	");
|
---|
70 | }
|
---|
71 | }
|
---|