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

Last change on this file since 6070 was 6070, checked in by stoecker, 11 years ago

see #8853 remove tabs, trailing spaces, windows line ends, strange characters

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