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

Last change on this file since 8530 was 8510, checked in by Don-vip, 9 years ago

checkstyle: enable relevant whitespace checks and fix them

  • Property svn:eol-style set to native
File size: 2.4 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[143]2package org.openstreetmap.josm.io;
[72]3
[5874]4import java.io.Closeable;
5import java.io.IOException;
[143]6import java.io.PrintWriter;
[72]7import java.util.HashMap;
[6316]8import java.util.Map;
[72]9
10/**
11 * Helper class to use for xml outputting classes.
[1169]12 *
[72]13 * @author imi
14 */
[5874]15public class XmlWriter implements Closeable {
[72]16
[5874]17 protected final PrintWriter out;
[1677]18
[1523]19 public XmlWriter(PrintWriter out) {
[1169]20 this.out = out;
21 }
[1677]22
[5874]23 /**
24 * Flushes the stream.
25 */
[4645]26 public void flush() {
[5874]27 if (out != null) {
28 out.flush();
29 }
[4645]30 }
31
[5146]32 public static String encode(String unencoded) {
33 return encode(unencoded, false);
34 }
35
[1169]36 /**
37 * Encode the given string in XML1.0 format.
38 * Optimized to fast pass strings that don't need encoding (normal case).
[5146]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
[6830]43 * new JLabel("<html>'</html>")
[5146]44 * literally as 6 character string, see #7558)
[1169]45 */
[5146]46 public static String encode(String unencoded, boolean keepApos) {
[1169]47 StringBuilder buffer = null;
48 for (int i = 0; i < unencoded.length(); ++i) {
[5146]49 String encS = null;
50 if (!keepApos || unencoded.charAt(i) != '\'') {
51 encS = XmlWriter.encoding.get(unencoded.charAt(i));
52 }
[1169]53 if (encS != null) {
[4645]54 if (buffer == null) {
[8510]55 buffer = new StringBuilder(unencoded.substring(0, i));
[4645]56 }
[1169]57 buffer.append(encS);
[4645]58 } else if (buffer != null) {
[1169]59 buffer.append(unencoded.charAt(i));
[4645]60 }
[1169]61 }
62 return (buffer == null) ? unencoded : buffer.toString();
63 }
[72]64
[1169]65 /**
66 * The output writer to save the values to.
67 */
[7005]68 private static final Map<Character, String> encoding = new HashMap<>();
[1169]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 }
[6070]79
[5874]80 @Override
81 public void close() throws IOException {
82 if (out != null) {
83 out.close();
84 }
85 }
[72]86}
Note: See TracBrowser for help on using the repository browser.