Java XML Node Replace replaceVariable(final Node node, final String var, final String valueString)

Here you can find the source of replaceVariable(final Node node, final String var, final String valueString)

Description

replace Variable

License

LGPL

Parameter

Parameter Description
node the node to do variable replacement in
var the variable name to replace
valueString the value to replace the variable name with

Declaration

public static void replaceVariable(final Node node, final String var, final String valueString) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

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 {
    /**/*from  ww w . j a  va2 s . c  o  m*/
     * @param node the node to do variable replacement in
     * @param var the variable name to replace
     * @param valueString the value to replace the variable name with
     */
    public static void replaceVariable(final Node node, final String var, final String valueString) {
        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);
                if (attr.getValue().contains("$(" + var + ")")) {
                    String att = attr.getValue();
                    att = att.replaceAll("\\$\\(" + var + "\\)", valueString);
                    attr.setNodeValue(att);
                }
            }
        }
        case Node.CDATA_SECTION_NODE: {
            String content = node.getTextContent();
            if (content.contains("$(" + var + ")")) {
                content = content.replaceAll("\\$\\(" + var + "\\)", valueString);
                node.setNodeValue(content);
            }
        }
        }

        // process children
        final NodeList children = node.getChildNodes();
        for (int childIndex = 0; childIndex < children.getLength(); childIndex++) {
            final Node child = children.item(childIndex);
            replaceVariable(child, var, valueString);
        }
    }
}

Related

  1. replaceComma(Node node)
  2. replaceNode(Node masterNode, Node oldNode, Node newNode)
  3. replaceNode(Node oldNode, Node newNode, Node source)
  4. replaceText(Node node, String text)
  5. replaceVariable(final Node node, final String sVar, final String sValue)
  6. replaceWith(Node currentNode, Node replacerNode)
  7. replaceWith(Node oldNode, Node newNode)