Java tutorial
//package com.java2s; //License from project: LGPL import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Pattern used to match variables in XML fragments. */ private static Pattern variablePattern = Pattern.compile("\\$\\(([^\\)]+)\\)"); /** * Identify variables in attribute values and CDATA contents and replace * with their values as defined in the variableDefs map. Variables without * definitions are left alone. * * @param node the node to do variable replacement in * @param variableDefs map from variable names to values. */ public static void replaceVariables(final Node node, Map<String, String> variableDefs) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: final Element element = (Element) node; final NamedNodeMap atts = element.getAttributes(); for (int i = 0; i < atts.getLength(); i++) { final Attr attr = (Attr) atts.item(i); attr.setNodeValue(replaceVariablesInString(attr.getValue(), variableDefs)); } break; case Node.CDATA_SECTION_NODE: String content = node.getTextContent(); node.setNodeValue(replaceVariablesInString(content, variableDefs)); break; default: break; } // process children final NodeList children = node.getChildNodes(); for (int childIndex = 0; childIndex < children.getLength(); childIndex++) replaceVariables(children.item(childIndex), variableDefs); } /** * Identify variables in the given string and replace with their values as * defined in the variableDefs map. Variables without definitions are left * alone. * * @param string String to do variable replacement in. * @param variableDefs Map from variable names to values. * @return modified string */ public static String replaceVariablesInString(String string, Map<String, String> variableDefs) { StringBuffer replacementStringBuffer = new StringBuffer(); Matcher variableMatcher = variablePattern.matcher(string); while (variableMatcher.find()) { String varString = variableMatcher.group(1).trim(); int eqIdx = varString.indexOf("="); String varName; if (eqIdx > -1) varName = varString.substring(0, eqIdx).trim(); else varName = varString; String replacementString = variableDefs.containsKey(varName) ? variableDefs.get(varName) : variableMatcher.group(0); variableMatcher.appendReplacement(replacementStringBuffer, Matcher.quoteReplacement(replacementString)); } variableMatcher.appendTail(replacementStringBuffer); return replacementStringBuffer.toString(); } }