01: /*
02: * Copyright (C) 2006 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 17. April 2006 by Mauro Talevi
11: */
12: package com.thoughtworks.xstream.io.xml;
13:
14: /**
15: * Allows replacement of Strings in XML-friendly drivers.
16: *
17: * The default replacements are:
18: * <ul>
19: * <li><b>$</b> (dollar) chars are replaced with <b>_-</b> (underscore dash) string.<br></li>
20: * <li><b>_</b> (underscore) chars are replaced with <b>__</b> (double underscore) string.<br></li>
21: * </ul>
22: *
23: * @author Mauro Talevi
24: * @author Jörg Schaible
25: * @since 1.2
26: */
27: public class XmlFriendlyReplacer {
28:
29: private String dollarReplacement;
30: private String underscoreReplacement;
31:
32: /**
33: * Default constructor.
34: */
35: public XmlFriendlyReplacer() {
36: this ("_-", "__");
37: }
38:
39: /**
40: * Creates an XmlFriendlyReplacer with custom replacements
41: * @param dollarReplacement the replacement for '$'
42: * @param underscoreReplacement the replacement for '_'
43: */
44: public XmlFriendlyReplacer(String dollarReplacement,
45: String underscoreReplacement) {
46: this .dollarReplacement = dollarReplacement;
47: this .underscoreReplacement = underscoreReplacement;
48: }
49:
50: /**
51: * Escapes name substituting '$' and '_' with replacement strings
52: * @param name the name of attribute or node
53: * @return The String with the escaped name
54: */
55: public String escapeName(String name) {
56: StringBuffer result = new StringBuffer();
57: int length = name.length();
58: for (int i = 0; i < length; i++) {
59: char c = name.charAt(i);
60: if (c == '$') {
61: result.append(dollarReplacement);
62: } else if (c == '_') {
63: result.append(underscoreReplacement);
64: } else {
65: result.append(c);
66: }
67: }
68: return result.toString();
69: }
70:
71: /**
72: * Unescapes name re-enstating '$' and '_' when replacement strings are found
73: * @param name the name of attribute or node
74: * @return The String with unescaped name
75: */
76: public String unescapeName(String name) {
77: final int underscoreReplacementInc = underscoreReplacement
78: .length() - 1;
79: final int dollarReplacementInc = dollarReplacement.length() - 1;
80: final int length = name.length();
81: final StringBuffer result = new StringBuffer();
82: for (int i = 0; i < length; i++) {
83: final char c = name.charAt(i);
84: if (name.startsWith(dollarReplacement, i)) {
85: i += dollarReplacementInc;
86: result.append('$');
87: } else if (name.startsWith(underscoreReplacement, i)) {
88: i += underscoreReplacementInc;
89: result.append('_');
90: } else {
91: result.append(c);
92: }
93: }
94: return result.toString();
95: }
96: }
|