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("\\$\\(([^\\)]+)\\)"); /** * Extract default values of variables defined in the DOM subtree below node. * Default values are used to populate the variableDefs map. Variables * already defined in this map will NOT be modified. * * @param node root node of DOM subtree to extract default values from. * @param variableDefs map which default values will be added to. */ public static void extractVariableDefaults(final Node node, Map<String, String> variableDefs) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: final Element element = (Element) node; final NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr) attrs.item(i); extractVariableDefaultsFromString(attr.getValue(), variableDefs); } break; case Node.CDATA_SECTION_NODE: String content = node.getTextContent(); extractVariableDefaultsFromString(content, variableDefs); break; default: break; } final NodeList children = node.getChildNodes(); for (int childIndex = 0; childIndex < children.getLength(); childIndex++) extractVariableDefaults(children.item(childIndex), variableDefs); } /** * Extract default values of variables defined in the given string. * Default values are used to populate the variableDefs map. Variables * already defined in this map will NOT be modified. * * @param string string to extract default values from. * @param variableDefs map which default values will be added to. */ public static void extractVariableDefaultsFromString(String string, Map<String, String> variableDefs) { Matcher variableMatcher = variablePattern.matcher(string); while (variableMatcher.find()) { String varString = variableMatcher.group(1); int eqIdx = varString.indexOf("="); if (eqIdx > -1) { String varName = varString.substring(0, eqIdx).trim(); if (!variableDefs.containsKey(varName)) variableDefs.put(varName, varString.substring(eqIdx + 1, varString.length())); } } } }