1 | package org.openstreetmap.josm.tools;
|
---|
2 |
|
---|
3 | import java.util.HashMap;
|
---|
4 |
|
---|
5 | /**
|
---|
6 | * Helper class to use for xml outputting classes.
|
---|
7 | *
|
---|
8 | * @author imi
|
---|
9 | */
|
---|
10 | public class XmlWriter {
|
---|
11 |
|
---|
12 | /**
|
---|
13 | * Encode the given string in XML1.0 format.
|
---|
14 | * Optimized to fast pass strings that don't need encoding (normal case).
|
---|
15 | */
|
---|
16 | public static String encode(String unencoded) {
|
---|
17 | StringBuilder buffer = null;
|
---|
18 | for (int i = 0; i < unencoded.length(); ++i) {
|
---|
19 | String encS = XmlWriter.encoding.get(unencoded.charAt(i));
|
---|
20 | if (encS != null) {
|
---|
21 | if (buffer == null)
|
---|
22 | buffer = new StringBuilder(unencoded.substring(0,i));
|
---|
23 | buffer.append(encS);
|
---|
24 | } else if (buffer != null)
|
---|
25 | buffer.append(unencoded.charAt(i));
|
---|
26 | }
|
---|
27 | return (buffer == null) ? unencoded : buffer.toString();
|
---|
28 | }
|
---|
29 |
|
---|
30 | /**
|
---|
31 | * @return The standard XML1.0 header. Encoding is utf-8
|
---|
32 | */
|
---|
33 | public static String header() {
|
---|
34 | return "<?xml version='1.0' encoding='UTF-8'?>";
|
---|
35 | }
|
---|
36 |
|
---|
37 |
|
---|
38 |
|
---|
39 | final private static HashMap<Character, String> encoding = new HashMap<Character, String>();
|
---|
40 | static {
|
---|
41 | encoding.put('<', "<");
|
---|
42 | encoding.put('>', ">");
|
---|
43 | encoding.put('"', """);
|
---|
44 | encoding.put('\'', "'");
|
---|
45 | encoding.put('&', "&");
|
---|
46 | encoding.put('\n', "
");
|
---|
47 | encoding.put('\r', "
");
|
---|
48 | encoding.put('\t', "	");
|
---|
49 | }
|
---|
50 | }
|
---|