Example usage for org.w3c.dom Node setNodeValue

List of usage examples for org.w3c.dom Node setNodeValue

Introduction

In this page you can find the example usage for org.w3c.dom Node setNodeValue.

Prototype

public void setNodeValue(String nodeValue) throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:Main.java

/**
 * Clones the given DOM node into the given DOM document.
 * /* ww w . ja v  a2  s .c o  m*/
 * @param node
 *            The DOM node to clone.
 * @param doc
 *            The target DOM document.
 * @return The cloned node in the target DOM document.
 */
public static Node cloneNode(Node node, Document doc) {
    Node clone = null;
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        clone = doc.createElement(node.getNodeName());
        NamedNodeMap attrs = node.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attrNode = attrs.item(i);
            Attr attrClone = doc.createAttribute(attrNode.getNodeName());
            attrClone.setNodeValue(attrNode.getNodeValue());
            ((Element) clone).setAttributeNode(attrClone);
        }

        // Iterate through each child nodes.
        NodeList childNodes = node.getChildNodes();
        if (childNodes != null) {
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node childNode = childNodes.item(i);
                if (childNode == null) {
                    continue;
                }
                Node childClone = cloneNode(childNode, doc);
                if (childClone == null) {
                    continue;
                }
                clone.appendChild(childClone);
            }
        }
        break;

    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE:
        clone = doc.createTextNode(node.getNodeName());
        clone.setNodeValue(node.getNodeValue());
        break;
    }
    return clone;
}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * Appends the specified value as a text node to the element. If the
 * value is <code>null</code>, the element's first child node will be
 * removed./*from   w  w  w .j a  v  a 2 s  . co  m*/
 *
 * @param element the element.
 * @param value   the element's value.
 */
public static void setElementValue(Element element, String value) {
    Node child = element.getFirstChild();

    if (value != null) {
        if (child == null) {
            child = element.getOwnerDocument().createTextNode("");
            element.appendChild(child);
        }

        child.setNodeValue(value);
    } else {
        if (child != null) {
            element.removeChild(child);
        }
    }
}

From source file:com.collabnet.ccf.core.recovery.HospitalArtifactReplayer.java

private void addGAImportComponents(Document document, Element routerElement) {
    NodeList propertyNodes = routerElement.getElementsByTagName("map");
    Element mapElement = (Element) propertyNodes.item(0);
    Element fileReaderEntry = document.createElement("entry");
    fileReaderEntry.setAttribute("key-ref", "FileReader");
    fileReaderEntry.setAttribute("value-ref", "GenericArtifactMultiLineParser");
    Element gaParserEntry = document.createElement("entry");
    gaParserEntry.setAttribute("key-ref", "GenericArtifactMultiLineParser");
    gaParserEntry.setAttribute("value-ref", entry.getSourceComponent());
    mapElement.appendChild(fileReaderEntry);
    mapElement.appendChild(gaParserEntry);

    Element documentElement = document.getDocumentElement();
    Element fileReaderElement = document.createElement("bean");
    fileReaderElement.setAttribute("id", "FileReader");
    fileReaderElement.setAttribute("class",
            "org.openadaptor.auxil.connector.iostream.reader.FileReadConnector");
    Element fileProperty = document.createElement("property");
    fileProperty.setAttribute("name", "filename");
    fileProperty.setAttribute("value", entry.getDataFile().getAbsolutePath());
    fileReaderElement.appendChild(fileProperty);
    documentElement.appendChild(fileReaderElement);

    Element gaParserElement = document.createElement("bean");
    gaParserElement.setAttribute("id", "GenericArtifactMultiLineParser");
    gaParserElement.setAttribute("class", "com.collabnet.ccf.core.utils.GenericArtifactMultiLineParser");

    documentElement.appendChild(gaParserElement);

    NodeList allBeans = document.getElementsByTagName("bean");
    String exceptionProcessorComponentName = null;
    for (int i = 0; i < allBeans.getLength(); i++) {
        Node beanNode = allBeans.item(i);
        NamedNodeMap atts = beanNode.getAttributes();
        Node beanIdNode = atts.getNamedItem("id");
        String beanId = beanIdNode.getNodeValue();
        // FIXME What happens if the router component is not called router
        if (beanId.equals("Router")) {
            NodeList routerPropertyNodes = ((Element) beanNode).getElementsByTagName("property");
            for (int j = 0; j < routerPropertyNodes.getLength(); j++) {
                Node propNode = routerPropertyNodes.item(j);
                NamedNodeMap routerPropAtts = propNode.getAttributes();
                Node nameNode = routerPropAtts.getNamedItem("name");
                String routerProperty = nameNode.getNodeValue();
                if (routerProperty.equals("exceptionProcessor")) {
                    Node expProcessorNode = routerPropAtts.getNamedItem("ref");
                    exceptionProcessorComponentName = expProcessorNode.getNodeValue();
                }//from w  w w .  j  a v a2 s.  co m
            }
        } else if (beanId.equals(exceptionProcessorComponentName)) {
            NodeList exceptionPropertyNodes = ((Element) beanNode).getElementsByTagName("property");
            for (int j = 0; j < exceptionPropertyNodes.getLength(); j++) {
                Node propertyNode = exceptionPropertyNodes.item(j);
                NamedNodeMap excepPropAtts = propertyNode.getAttributes();
                Node nameNode = excepPropAtts.getNamedItem("name");
                String propertyName = nameNode.getNodeValue();
                if (propertyName.equals("hospitalFileName")) {
                    Node valueNode = excepPropAtts.getNamedItem("value");
                    valueNode.setNodeValue(replayWorkDir.getAbsolutePath() + File.separator + "hospital.txt");
                } else if (propertyName.equals("artifactsDirectory")) {
                    Node valueNode = excepPropAtts.getNamedItem("value");
                    valueNode.setNodeValue(replayWorkDir.getAbsolutePath() + File.separator + "artifacts");
                }
            }
        }
    }
}

From source file:com.intuit.karate.Script.java

public static void evalXmlEmbeddedExpressions(Node node, ScriptContext context) {
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        node = node.getFirstChild();/*from   ww  w .j  av a2 s.  c o m*/
    }
    NamedNodeMap attribs = node.getAttributes();
    int attribCount = attribs.getLength();
    for (int i = 0; i < attribCount; i++) {
        Attr attrib = (Attr) attribs.item(i);
        String value = attrib.getValue();
        value = StringUtils.trimToEmpty(value);
        if (isEmbeddedExpression(value)) {
            try {
                ScriptValue sv = evalInNashorn(value.substring(1), context);
                attrib.setValue(sv.getAsString());
            } catch (Exception e) {
                logger.warn("embedded xml-attribute script eval failed: {}", e.getMessage());
            }
        }
    }
    NodeList nodes = node.getChildNodes();
    int childCount = nodes.getLength();
    for (int i = 0; i < childCount; i++) {
        Node child = nodes.item(i);
        String value = child.getNodeValue();
        if (value != null) {
            value = StringUtils.trimToEmpty(value);
            if (isEmbeddedExpression(value)) {
                try {
                    ScriptValue sv = evalInNashorn(value.substring(1), context);
                    child.setNodeValue(sv.getAsString());
                } catch (Exception e) {
                    logger.warn("embedded xml-text script eval failed: {}", e.getMessage());
                }
            }
        } else if (child.hasChildNodes()) {
            evalXmlEmbeddedExpressions(child, context);
        }
    }
}

From source file:com.hygenics.parser.ManualReplacement.java

private void transform() {
    log.info("Transforming");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    for (String fpath : fpaths) {
        log.info("FILE: " + fpath);
        try {//from w  w  w .j  a  va 2s.c  o  m
            // TRANSFORM
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(fpath));
            Node root = doc.getFirstChild();
            XPathFactory xfactory = XPathFactory.newInstance();
            XPath xpath = xfactory.newXPath();
            String database = null;
            String path = "//transformation/connection";

            log.info("Removing");
            for (String dbname : remove) {
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                if (conn != null) {
                    root.removeChild(conn);
                }
            }

            log.info("Transforming");
            for (String key : databaseAttributes.keySet()) {
                database = key;
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);

                if (conn != null) {
                    if (remove.contains(key)) {
                        root.removeChild(conn);
                    } else {
                        Map<String, String> attrs = databaseAttributes.get(database);
                        NodeList nl = conn.getChildNodes();
                        Set<String> keys = databaseAttributes.get(key).keySet();

                        for (int i = 0; i < nl.getLength(); i++) {
                            org.w3c.dom.Node n = nl.item(i);

                            if (keys.contains(n.getNodeName().trim())) {
                                n.setNodeValue(attrs.get(n.getNodeName()));
                            }
                        }
                    }
                }

                if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) {
                    log.info("Logging Manipulation");
                    log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null
                            ? "Removing Logging Data"
                            : "Adding Logging data");
                    String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table",
                            "step-log-table", "metrics-log-table" };
                    for (String section : sections) {
                        log.info("Changing Settings for " + section);
                        xepr = xpath.compile("//" + section + "/field/enabled");
                        NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET);
                        log.info("Nodes Found: " + Integer.toString(nodes.getLength()));
                        for (int i = 0; i < nodes.getLength(); i++) {
                            if (!this.log_to_table) {
                                nodes.item(i).setNodeValue("N");
                            } else {
                                nodes.item(i).setNodeValue("Y");
                            }
                        }

                        for (String nodeName : new String[] { "schema", "connection", "table",
                                "size_limit_lines", "interval", "timeout_days" }) {
                            if (!this.log_to_table) {
                                log.info("Changing Settings for Node: " + nodeName);
                                xepr = xpath.compile("//" + section + "/" + nodeName);
                                Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                                if (node != null) {
                                    if (!this.log_to_table) {
                                        node.setNodeValue(null);
                                    } else if (this.loggingTables.containsKey(section)
                                            && this.loggingTables.get(section).containsKey(nodeName)) {
                                        node.setNodeValue(this.loggingTables.get(section).get(nodeName));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // SET MAIN CONNECTION
            if (mainConnection != null) {
                XPathExpression xepr = xpath.compile(path);
                NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of
                // org.w3c it is
                // actually a NodeList
                for (int i = 0; i < conns.getLength(); i++) {
                    if (!conns.item(i).hasChildNodes()) {// only connection
                        // elements
                        // without child
                        // nodes have
                        // text content
                        conns.item(i).setNodeValue(mainConnection);
                    }
                }
            }

            if (this.replacements != null) {
                for (String key : this.replacements.keySet()) {
                    XPathExpression xepr = xpath.compile(key);
                    Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                    if (node != null) {
                        for (String attrVal : this.replacements.get(key).keySet()) {
                            log.info("Replacing Information at " + key + "at " + attrVal);
                            log.info("Replacement Will Be: "
                                    + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));

                            if (attrVal.toLowerCase().trim().equals("text")) {
                                node.setNodeValue(
                                        StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));
                                if (node.getNodeValue() == null) {
                                    node.setTextContent(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                }

                            } else {
                                NamedNodeMap nattrs = node.getAttributes();
                                Node n = nattrs.getNamedItem(attrVal);
                                if (n != null) {
                                    n.setNodeValue(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                } else {
                                    log.warn("Attribute Not Found " + attrVal);
                                }
                            }
                        }
                    } else {
                        log.warn("Node not found for " + key);
                    }
                }
            }

            // WRITE TO FILE
            log.info("Writing to File");
            TransformerFactory tfact = TransformerFactory.newInstance();
            Transformer transformer = tfact.newTransformer();
            DOMSource source = new DOMSource(doc);
            try (FileOutputStream stream = new FileOutputStream(new File(fpath))) {
                StreamResult result = new StreamResult(stream);
                transformer.transform(source, result);
                stream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

private void setParamAsChild(Element eSection, String sName, String sValue) throws DOMException {
    boolean bFound = false;

    //check if child allready exists
    NodeList nlChilds = eSection.getChildNodes();
    for (int i = 0; i < nlChilds.getLength(); i++) {
        Node nTemp = nlChilds.item(i);
        //check if tagname = configItem
        if (nTemp != null && nTemp.getNodeName().equalsIgnoreCase(sName)) {
            NodeList nlSubNodes = nTemp.getChildNodes();
            for (int iIter2 = 0; iIter2 < nlSubNodes.getLength(); iIter2++) {
                Node nSubTemp = nlSubNodes.item(iIter2);
                if (nSubTemp.getNodeType() == Node.TEXT_NODE) {
                    nSubTemp.setNodeValue(sValue);
                    bFound = true;// w w w .j a va  2  s  .  c  o  m
                }
            }
        }
    }

    if (!bFound) //add new child
    {
        //create new child
        Node nValue = _oDomDocument.createTextNode(sValue);
        Element nConfigItem = _oDomDocument.createElement(sName);
        nConfigItem.appendChild(nValue);

        //append child
        eSection.appendChild(nConfigItem);
    }
}

From source file:jp.ikedam.jenkins.plugins.jobcopy_builder.ReplaceRegExpOperation.java

/**
 * Returns modified XML Document of the job configuration.
 *
 * Replace the strings in the job configuration: only applied to strings in text nodes, so the XML structure is never destroyed.
 *
 * @param doc//from  w  ww.j a  v a2s . c  om
 *            XML Document of the job to be copied (job/NAME/config.xml)
 * @param env
 *            Variables defined in the build.
 * @param logger
 *            The output stream to log.
 * @return modified XML Document. Return null if an error occurs.
 * @see jp.ikedam.jenkins.plugins.jobcopy_builder.AbstractXmlJobcopyOperation#perform(org.w3c.dom.Document, hudson.EnvVars, java.io.PrintStream)
 */
@Override
public Document perform(final Document doc, final EnvVars env, final PrintStream logger) {
    final String fromStr = getFromStr();
    String toStr = getToStr();

    if (StringUtils.isEmpty(fromStr)) {
        logger.println("From String is empty");
        return null;
    }
    if (toStr == null) {
        toStr = "";
    }
    final String expandedFromStr = isExpandFromStr() ? env.expand(fromStr) : maskSpecialChars(fromStr);

    Pattern pattern;
    try {
        pattern = Pattern.compile(expandedFromStr);
    } catch (final PatternSyntaxException e) {
        logger.println("Error on regular expression: " + e.getMessage());
        return null;
    }

    String expandedToStr = isExpandToStr() ? env.expand(toStr) : maskSpecialChars(toStr);
    if (StringUtils.isEmpty(expandedFromStr)) {
        logger.println("From String got to be empty");
        return null;
    }
    if (expandedToStr == null) {
        expandedToStr = "";
    }

    logger.print("Replacing with RegExp: " + expandedFromStr + " -> " + expandedToStr);
    try {
        // Retrieve all text nodes.
        final NodeList textNodeList = getNodeList(doc, "//text()");

        // Perform replacing to all text nodes.
        // NodeList does not implement Collection, and foreach is not usable.
        for (int i = 0; i < textNodeList.getLength(); ++i) {
            final Node node = textNodeList.item(i);
            final String nodeValue = node.getNodeValue();
            String newNodeValue = nodeValue;
            final Matcher matcher = pattern.matcher(nodeValue);
            // check all occurance
            while (matcher.find()) {
                newNodeValue = matcher.replaceAll(expandedToStr);
            }
            node.setNodeValue(newNodeValue);
        }
        logger.println("");

        return doc;
    } catch (final Exception e) {
        logger.print("Error occured in XML operation");
        e.printStackTrace(logger);
        return null;
    }
}

From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java

private void modifyAccessElementAttributes(Document emlDocument) throws TransformerException {
    CachedXPathAPI xpathapi = new CachedXPathAPI();

    // Parse the access elements
    NodeList accessNodeList = xpathapi.selectNodeList(emlDocument, ACCESS_PATH);
    if (accessNodeList != null) {
        for (int i = 0; i < accessNodeList.getLength(); i++) {
            boolean hasSystemAttribute = false;
            Element accessElement = (Element) accessNodeList.item(i);
            NamedNodeMap accessAttributesList = accessElement.getAttributes();

            for (int j = 0; j < accessAttributesList.getLength(); j++) {
                Node attributeNode = accessAttributesList.item(j);
                String nodeName = attributeNode.getNodeName();
                String nodeValue = attributeNode.getNodeValue();
                if (nodeName.equals("authSystem")) {
                    attributeNode.setNodeValue(LEVEL_ONE_AUTH_SYSTEM_ATTRIBUTE);
                } else if (nodeName.equals("system")) {
                    attributeNode.setNodeValue(LEVEL_ONE_SYSTEM_ATTRIBUTE);
                    hasSystemAttribute = true;
                }/* w  ww .  j  a  v  a  2s . c om*/
            }

            /*
             * No @system attribute was found in the access element, so we
             * need to add one.
             */
            if (!hasSystemAttribute) {
                Attr systemAttribute = emlDocument.createAttribute("system");
                systemAttribute.setTextContent(LEVEL_ONE_SYSTEM_ATTRIBUTE);
                accessElement.setAttributeNode(systemAttribute);
            }
        }
    }
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void insertBefore(NodeList nodes, Node newNode, short newNodeType) {
    Node currentNode = nodes.item(0);
    switch (newNodeType) {
    case Node.ATTRIBUTE_NODE:
        Element parent = ((Attr) currentNode).getOwnerElement();
        parent.setAttributeNode((Attr) newNode);
        break;/*from  w ww .jav  a2  s .com*/
    case Node.ELEMENT_NODE:
        currentNode.getParentNode().insertBefore(newNode, currentNode);
        break;
    case Node.TEXT_NODE:
        String v = currentNode.getNodeValue();
        currentNode.setNodeValue(newNode.getNodeValue() + v);
        break;
    }
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void replace(NodeList nodes, Node newNode, short newNodeType) {
    Node currentNode = nodes.item(0);
    switch (newNodeType) {
    case Node.ATTRIBUTE_NODE:
        Element parent = ((Attr) currentNode).getOwnerElement();
        parent.removeAttributeNode((Attr) currentNode);
        parent.setAttributeNode((Attr) newNode);
        break;//from   w w w.  ja  v a 2  s . c o m
    case Node.ELEMENT_NODE:
        currentNode.getParentNode().replaceChild(newNode, currentNode);
        break;
    case Node.TEXT_NODE:
        currentNode.setNodeValue(newNode.getNodeValue());
        break;
    }
}