Java tutorial
//package com.java2s; public class Main { private static final String MAP_OPEN = "<map>"; private static final String MAP_CLOSE = "</map>"; private static final String MAP_EMPTY = "<map/>"; private static final String ENTRY_OPEN = "<entry>"; private static final String ENTRY_CLOSE = "</entry>"; private static final String VALUE_OPEN = "<string>"; private static final String VALUE_CLOSE = "</string>"; public static String addParam(String key, String value, String srcStr) { if (srcStr == null || srcStr.startsWith(MAP_EMPTY)) { StringBuilder sb = new StringBuilder(); sb.append(MAP_OPEN); addEntry(sb, key, value); sb.append(MAP_CLOSE); return sb.toString(); } if (srcStr.startsWith(MAP_OPEN)) { StringBuilder sb = new StringBuilder(); sb.append(MAP_OPEN); addEntry(sb, key, value); sb.append(srcStr.substring(MAP_OPEN.length())); return sb.toString(); } return srcStr; } private static void addEntry(StringBuilder sb, String key, String value) { if (key == null || value == null) { throw new IllegalArgumentException("key or value is null"); } sb.append(ENTRY_OPEN); sb.append(VALUE_OPEN); escapeElementEntities(sb, key); sb.append(VALUE_CLOSE); sb.append(VALUE_OPEN); escapeElementEntities(sb, value); sb.append(VALUE_CLOSE); sb.append(ENTRY_CLOSE); } private static void escapeElementEntities(StringBuilder sb, String text) { for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; default: sb.append(c); } } } }