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

Last change on this file since 1023 was 627, checked in by framm, 16 years ago
  • Property svn:eol-style set to native
File size: 2.2 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.io;
3
4import java.io.OutputStream;
5import java.io.OutputStreamWriter;
6import java.io.PrintWriter;
7import java.io.UnsupportedEncodingException;
8import java.util.HashMap;
9
10/**
11 * Helper class to use for xml outputting classes.
12 *
13 * @author imi
14 */
15public class XmlWriter {
16
17 /**
18 * The interface to write the data into an Osm stream
19 * @author immanuel.scholz
20 */
21 public static interface OsmWriterInterface {
22 void header(PrintWriter out);
23 void write(PrintWriter out);
24 void footer(PrintWriter out);
25 }
26
27
28 protected XmlWriter(PrintWriter out) {
29 this.out = out;
30 }
31
32 /**
33 * Encode the given string in XML1.0 format.
34 * Optimized to fast pass strings that don't need encoding (normal case).
35 */
36 public static String encode(String unencoded) {
37 StringBuilder buffer = null;
38 for (int i = 0; i < unencoded.length(); ++i) {
39 String encS = XmlWriter.encoding.get(unencoded.charAt(i));
40 if (encS != null) {
41 if (buffer == null)
42 buffer = new StringBuilder(unencoded.substring(0,i));
43 buffer.append(encS);
44 } else if (buffer != null)
45 buffer.append(unencoded.charAt(i));
46 }
47 return (buffer == null) ? unencoded : buffer.toString();
48 }
49
50 /**
51 * Write the header and start tag, then call the runnable to add all real tags and finally
52 * "closes" the xml by writing the footer.
53 */
54 public static void output(OutputStream outStream, OsmWriterInterface outputWriter) {
55 PrintWriter out;
56 try {
57 out = new PrintWriter(new OutputStreamWriter(outStream, "UTF-8"));
58 } catch (UnsupportedEncodingException e) {
59 throw new RuntimeException(e);
60 }
61 out.println("<?xml version='1.0' encoding='UTF-8'?>");
62 outputWriter.header(out);
63 outputWriter.write(out);
64 outputWriter.footer(out);
65 out.flush();
66 out.close();
67 }
68
69 /**
70 * The output writer to save the values to.
71 */
72 protected final PrintWriter out;
73 final private static HashMap<Character, String> encoding = new HashMap<Character, String>();
74 static {
75 encoding.put('<', "&lt;");
76 encoding.put('>', "&gt;");
77 encoding.put('"', "&quot;");
78 encoding.put('\'', "&apos;");
79 encoding.put('&', "&amp;");
80 encoding.put('\n', "&#xA;");
81 encoding.put('\r', "&#xD;");
82 encoding.put('\t', "&#x9;");
83 }
84}
Note: See TracBrowser for help on using the repository browser.