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 | /**
|
---|
25 | * Encode the given string in XML1.0 format.
|
---|
26 | * Optimized to fast pass strings that don't need encoding (normal case).
|
---|
27 | */
|
---|
28 | public static String encode(String unencoded) {
|
---|
29 | StringBuilder buffer = null;
|
---|
30 | for (int i = 0; i < unencoded.length(); ++i) {
|
---|
31 | String encS = XmlWriter.encoding.get(unencoded.charAt(i));
|
---|
32 | if (encS != null) {
|
---|
33 | if (buffer == null) {
|
---|
34 | buffer = new StringBuilder(unencoded.substring(0,i));
|
---|
35 | }
|
---|
36 | buffer.append(encS);
|
---|
37 | } else if (buffer != null) {
|
---|
38 | buffer.append(unencoded.charAt(i));
|
---|
39 | }
|
---|
40 | }
|
---|
41 | return (buffer == null) ? unencoded : buffer.toString();
|
---|
42 | }
|
---|
43 |
|
---|
44 | /**
|
---|
45 | * The output writer to save the values to.
|
---|
46 | */
|
---|
47 | final private static HashMap<Character, String> encoding = new HashMap<Character, String>();
|
---|
48 | static {
|
---|
49 | encoding.put('<', "<");
|
---|
50 | encoding.put('>', ">");
|
---|
51 | encoding.put('"', """);
|
---|
52 | encoding.put('\'', "'");
|
---|
53 | encoding.put('&', "&");
|
---|
54 | encoding.put('\n', "
");
|
---|
55 | encoding.put('\r', "
");
|
---|
56 | encoding.put('\t', "	");
|
---|
57 | }
|
---|
58 | }
|
---|