1 package com.thoughtworks.xstream.mapper; 2 3 import com.thoughtworks.xstream.alias.ClassMapper; 4 5 14 public class XmlFriendlyMapper extends MapperWrapper { 15 16 public XmlFriendlyMapper(ClassMapper wrapped) { 17 super(wrapped); 18 } 19 20 public String serializedClass(Class type) { 21 String name = super.serializedClass(type); 22 23 name = name.replace('$', '-'); 25 26 if (name.charAt(0) == '-') { 28 name = "default" + name; 29 } 30 31 return name; 32 } 33 34 public Class realClass(String elementName) { 35 36 if (elementName.startsWith("default-")) { 38 elementName = elementName.substring(7); 39 } 40 41 elementName = elementName.replace('-', '$'); 43 44 return super.realClass(elementName); 45 } 46 47 public String serializedMember(Class type, String memberName) { 48 return escape(super.serializedMember(type, memberName)); 49 } 50 51 public String realMember(Class type, String serialized) { 52 return unescape(super.realMember(type, serialized)); 53 } 54 55 public String mapNameToXML(String javaName) { 56 return escape(javaName); 57 } 58 59 public String mapNameFromXML(String xmlName) { 60 return unescape(xmlName); 61 } 62 63 private String unescape(String xmlName) { 64 StringBuffer result = new StringBuffer (); 65 int length = xmlName.length(); 66 for(int i = 0; i < length; i++) { 67 char c = xmlName.charAt(i); 68 if (c == '_') { 69 if (xmlName.charAt(i + 1) == '_') { 70 i++; 71 result.append('_'); 72 } else if (xmlName.length() >= i + 8 && xmlName.substring(i + 1, i + 8).equals("DOLLAR_")) { 73 i += 7; 74 result.append('$'); 75 } 76 } else { 77 result.append(c); 78 } 79 } 80 return result.toString(); 81 } 82 83 private String escape(String javaName) { 84 StringBuffer result = new StringBuffer (); 85 int length = javaName.length(); 86 for(int i = 0; i < length; i++) { 87 char c = javaName.charAt(i); 88 if (c == '$') { 89 result.append("_DOLLAR_"); 90 } else if (c == '_') { 91 result.append("__"); 92 } else { 93 result.append(c); 94 } 95 } 96 return result.toString(); 97 } 98 99 } 100 | Popular Tags |