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

Last change on this file since 8263 was 7005, checked in by Don-vip, 10 years ago

see #8465 - use diamond operator where applicable

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