Java XML Node Replace replaceVariable(final Node node, final String sVar, final String sValue)

Here you can find the source of replaceVariable(final Node node, final String sVar, final String sValue)

Description

replace Variable

License

Open Source License

Parameter

Parameter Description
node the node to do variable replacement in
sVar the variable name to replace
sValue the value to replace the variable name with

Declaration

public static void replaceVariable(final Node node, final String sVar,
        final String sValue) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import org.w3c.dom.*;

public class Main {
    /**//from   w  w  w  .  j  av  a2s .  co m
     * @param node the node to do variable replacement in
     * @param sVar the variable name to replace
     * @param sValue the value to replace the variable name with
     */
    public static void replaceVariable(final Node node, final String sVar,
            final String sValue) {
        if (node.getNodeType() == 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("$(" + sVar + ")")) {
                    String sAtt = attr.getValue();
                    sAtt = sAtt.replaceAll("\\$\\(" + sVar + "\\)", sValue);
                    attr.setNodeValue(sAtt);
                }
            }
        }

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

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 var, final String valueString)
  6. replaceWith(Node currentNode, Node replacerNode)
  7. replaceWith(Node oldNode, Node newNode)