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