TreeConverterUtil { public static String escape(String s) { StringBuilder sb = new StringBuilder(s.length()); int start = 0; char[] cs = s.toCharArray(); for (int idx = 0; idx < cs.length; idx++) { char c = cs[idx]; if (shouldEscape(c)) { sb.append(cs, start, idx - start); sb.append(ESCAPE_CHAR); if (c == ESCAPE_CHAR) { sb.append(c); } else { String asHex = Integer.toHexString(c); switch (asHex.length()) { case 1: sb.append("x0"); break; case 2: sb.append("x"); break; case 3: sb.append("u0"); break; case 4: sb.append("u"); break; default: throw new IllegalArgumentException(); } sb.append(asHex); } start = idx + 1; } } if (start < s.length()) { sb.append(cs, start, s.length() - start); } return sb.toString(); } private  TreeConverterUtil(); static String unescape(String s); static String escape(String s);  }
@Test public void testEscape() throws Exception { assertEquals("", escape("")); assertEquals("__a__b__", escape("_a_b_")); assertEquals("_x3a0_x3a1", escape(":0:1")); assertEquals("testTEST05", escape("testTEST05")); assertEquals("a_xa9c", escape("a\u00a9c")); assertEquals("a_u037ec", escape("a\u037ec")); assertEquals("a_ue1acd", escape("a\ue1acd")); }