source: josm/trunk/src/org/openstreetmap/josm/io/InvalidXmlCharacterFilter.java@ 6113

Last change on this file since 6113 was 6080, checked in by bastiK, 11 years ago

fixed #8893 - Cannot load GPX file

File size: 1.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import java.io.IOException;
5import java.io.Reader;
6
7import org.openstreetmap.josm.Main;
8
9/**
10 * FilterInputStream that gets rid of characters that are invalid in an XML 1.0
11 * document.
12 *
13 * Although these characters are forbidden, in the real wold they still appear
14 * in XML files. Java's SAX parser throws an exception, so we have to filter
15 * at a lower level.
16 *
17 * Only handles control characters (<0x20). Invalid characters are replaced
18 * by space (0x20).
19 */
20public class InvalidXmlCharacterFilter extends Reader {
21
22 private Reader reader;
23
24 public static boolean firstWarning = true;
25
26 public static final boolean[] INVALID_CHARS;
27
28 static {
29 INVALID_CHARS = new boolean[0x20];
30 for (int i = 0; i < INVALID_CHARS.length; ++i) {
31 INVALID_CHARS[i] = true;
32 }
33 INVALID_CHARS[0x9] = false; // tab
34 INVALID_CHARS[0xA] = false; // LF
35 INVALID_CHARS[0xD] = false; // CR
36 }
37
38 public InvalidXmlCharacterFilter(Reader reader) {
39 this.reader = reader;
40 }
41
42 @Override
43 public int read(char[] b, int off, int len) throws IOException {
44 int n = reader.read(b, off, len);
45 if (n == -1) {
46 return -1;
47 }
48 for (int i = off; i < off + n; ++i) {
49 b[i] = filter(b[i]);
50 }
51 return n;
52 }
53
54 @Override
55 public void close() throws IOException {
56 reader.close();
57 }
58
59 private char filter(char in) {
60 if (in < 0x20 && in >= 0 && INVALID_CHARS[in]) {
61 if (firstWarning) {
62 Main.warn("Invalid xml character encountered.");
63 firstWarning = false;
64 }
65 return 0x20;
66 }
67 return in;
68 }
69
70}
Note: See TracBrowser for help on using the repository browser.