Example usage for org.w3c.dom Node replaceChild

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

Introduction

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

Prototype

public Node replaceChild(Node newChild, Node oldChild) throws DOMException;

Source Link

Document

Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.

Usage

From source file:DOMUtil.java

/**
 * Automatically set text in a Node. Basically we find the first
 * Text node beneath the current node and replace it with a
 * CDATASection for the incoming text. All other Text nodes are
 * removed. Throws a DOMException if it's illegal to add a Text
 * child to the particular node./*from   ww w.j a va  2 s  . c o m*/
 *
 * @param node the starting node for the search.
 * @param text the text to be set
 * @param allowMarkupInText whether to allow markup in text to pass through unparsed
 * @return the updated node
 * @throws DOMException if the Text object is not found
 */
public static Node setTextInNode(Node node, String text, boolean allowMarkupInText) {
    //start by setting the value in the first text node we find with a comment
    Comment comment = node.getOwnerDocument().createComment("");
    Node newNode = null;

    //csc_092701.1 - support both encoded/unencoded text
    if (allowMarkupInText)
        newNode = node.getOwnerDocument().createCDATASection(text);
    else
        newNode = node.getOwnerDocument().createTextNode(text);
    //System.out.println ("newNode: "+newNode);

    Text textComp = DOMUtil.findFirstText((Element) node);
    //System.out.println ("textComp:"+textComp);        
    if (textComp == null) {
        node.appendChild(comment);
    } else {
        Node parent = textComp.getParentNode();
        parent.replaceChild(comment, textComp);
    }

    //now remove all the rest of the text nodes
    removeAllTextNodes(node);

    //now replace the comment with the newNode
    Node parent = comment.getParentNode();
    parent.replaceChild(newNode, comment);
    //System.out.println ("parent:  "+parent);        
    //System.out.println ("result:  "+DOMUtil.findFirstText((Element) parent));        
    //DOMUtil.printStackTrace(parent.getOwnerDocument().getDocumentElement());
    return node;
}

From source file:Main.java

public static void nodeSubUpdate(Element root, String table, String queryType, String queryValue) {
    Node find = getTag(root, table);
    Document doc = find.getOwnerDocument();

    NodeList nl = find.getChildNodes();
    int numnodes = nl.getLength();

    System.out.println("length : " + numnodes);

    Node replNode = null;/*from   w  w w . java 2s .c  o m*/

    for (int i = 0; i < numnodes; i++) {
        Node n = nl.item(i);
        String name = n.getNodeName();

        if (name.equals(queryType)) {
            replNode = n;
            System.out.println("Finding Node : " + replNode.getNodeName());

            break;
        }
    }

    Element type = doc.createElement(queryType);
    Text value = doc.createTextNode(queryValue);

    type.appendChild(value);

    find.replaceChild(type, replNode);

    print(doc);
}

From source file:Main.java

public static Element getElement(Document document, String[] path, String value, String translate,
        String module) {/*from   ww w .  ja v a 2s. c o  m*/
    Node node = document;
    NodeList list;
    for (int i = 0; i < path.length; ++i) {
        list = node.getChildNodes();
        boolean found = false;
        for (int j = 0; j < list.getLength(); ++j) {
            Node testNode = list.item(j);
            if (testNode.getNodeName().equals(path[i])) {
                found = true;
                node = testNode;
                break;
            }
        }
        if (found == false) {
            Element element = document.createElement(path[i]);
            node.appendChild(element);
            node = element;
        }
    }
    if (value != null) {
        Text text = document.createTextNode(value);
        list = node.getChildNodes();
        boolean found = false;
        for (int j = 0; j < list.getLength(); ++j) {
            Node testNode = list.item(j);
            if (testNode instanceof Text) {
                node.replaceChild(text, testNode);
                found = true;
                break;
            }
        }
        if (!found)
            node.appendChild(text);
    }
    if (node instanceof Element) {
        Element element = (Element) node;
        if (translate != null && element.getAttribute("translate").equals("")) {
            element.setAttribute("translate", translate);
        }
        if (module != null && element.getAttribute("module").equals("")) {
            element.setAttribute("module", module);
        }
    }
    return (Element) node;
}

From source file:Main.java

private static Node replaceTagName(Document document, Node node, String... tags) {

    NodeList nodeList = node.getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node subNode = nodeList.item(i);
        if (subNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }/*from   w  w w. j  av  a  2  s .  c  o m*/

        String nodeName = subNode.getNodeName();
        for (int j = 0; j < tags.length / 2; j++) {
            if (nodeName.equals(tags[j])) {
                Element element = document.createElement(tags[j + 1]);
                for (int k = 0; k < subNode.getChildNodes().getLength(); k++) {
                    element.appendChild(subNode.getChildNodes().item(k));
                }

                node.replaceChild(element, subNode);
                subNode = element;
            }
        }

        replaceTagName(document, subNode, tags);
    }

    return node;
}

From source file:com.rapidminer.gui.OperatorDocLoader.java

/**
 * /*  w  w w. ja  v  a 2s  . c om*/
 * @param operatorWikiName
 * @param opDesc
 * @return The parsed <tt>Document</tt> (not finally parsed) of the selected operator.
 * @throws MalformedURLException
 * @throws ParserConfigurationException
 */
private static Document parseDocumentForOperator(String operatorWikiName, OperatorDescription opDesc)
        throws MalformedURLException, ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setIgnoringComments(true);
    builderFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new XHTMLEntityResolver());

    Document document = null;
    URL url = new URL(WIKI_PREFIX_FOR_OPERATORS + operatorWikiName);
    if (url != null) {
        try {
            document = documentBuilder.parse(WebServiceTools.openStreamFromURL(url));
        } catch (IOException e) {
            logger.warning("Could not open " + url.toExternalForm() + ": " + e.getMessage());
        } catch (SAXException e) {
            logger.warning("Could not parse operator documentation: " + e.getMessage());
        }

        int i = 0;

        if (document != null) {
            Element contentElement = document.getElementById("content");

            // removing content element from document
            if (contentElement != null) {
                contentElement.getParentNode().removeChild(contentElement);
            }

            // removing everything from body
            NodeList bodies = document.getElementsByTagName("body");
            for (int k = 0; k < bodies.getLength(); k++) {
                Node body = bodies.item(k);
                while (body.hasChildNodes()) {
                    body.removeChild(body.getFirstChild());
                }

                // read content element to body
                if (contentElement != null && k == 0) {
                    body.appendChild(contentElement);
                }
            }

            // removing everything from head
            NodeList heads = document.getElementsByTagName("head");
            for (int k = 0; k < heads.getLength(); k++) {
                Node head = heads.item(k);
                while (head.hasChildNodes()) {
                    head.removeChild(head.getFirstChild());
                }
            }
            // removing...<head/> from document
            if (heads != null) {
                while (i < heads.getLength()) {
                    Node head = heads.item(i);
                    head.getParentNode().removeChild(head);
                }
            }

            // removing jump-to-nav element from document
            Element jumpToNavElement = document.getElementById("jump-to-nav");
            if (jumpToNavElement != null) {
                jumpToNavElement.getParentNode().removeChild(jumpToNavElement);
            }

            // removing mw-normal-catlinks element from document
            Element mwNormalCatlinksElement = document.getElementById("mw-normal-catlinks");
            if (mwNormalCatlinksElement != null) {
                mwNormalCatlinksElement.getParentNode().removeChild(mwNormalCatlinksElement);
            }

            // removing complete link navigation
            Element tocElement = document.getElementById("toc");
            if (tocElement != null) {
                tocElement.getParentNode().removeChild(tocElement);
            }

            // removing everything from class printfooter
            NodeList nodeListDiv = document.getElementsByTagName("div");
            for (int k = 0; k < nodeListDiv.getLength(); k++) {
                Element div = (Element) nodeListDiv.item(k);
                if (div.getAttribute("class").equals("printfooter")) {
                    div.getParentNode().removeChild(div);
                }
            }

            // removing everything from class editsection
            NodeList spanList = document.getElementsByTagName("span");
            for (int k = 0; k < spanList.getLength(); k++) {
                Element span = (Element) spanList.item(k);
                if (span.getAttribute("class").equals("editsection")) {
                    span.getParentNode().removeChild(span);
                }
            }

            // Synopsis Header
            boolean doIt = true;
            NodeList pList = document.getElementsByTagName("p");
            for (int k = 0; k < pList.getLength(); k++) {

                if (doIt) {
                    Node p = pList.item(k);
                    NodeList pChildList = p.getChildNodes();

                    for (int j = 0; j < pChildList.getLength(); j++) {

                        Node pChild = pChildList.item(j);
                        if (pChild.getNodeType() == Node.TEXT_NODE && pChild.getNodeValue() != null
                                && StringUtils.isNotBlank(pChild.getNodeValue())
                                && StringUtils.isNotEmpty(pChild.getNodeValue())) {

                            String pChildString = pChild.getNodeValue();
                            Element newPWithoutSpaces = document.createElement("p");
                            newPWithoutSpaces.setTextContent(pChildString);

                            Node synopsis = document.createTextNode("Synopsis");

                            Element span = document.createElement("span");
                            span.setAttribute("class", "mw-headline");
                            span.setAttribute("id", "Synopsis");
                            span.appendChild(synopsis);

                            Element h2 = document.createElement("h2");
                            h2.appendChild(span);

                            Element div = document.createElement("div");
                            div.setAttribute("id", "synopsis");
                            div.appendChild(h2);
                            div.appendChild(newPWithoutSpaces);

                            Node pChildParentParent = pChild.getParentNode().getParentNode();
                            Node pChildParent = pChild.getParentNode();

                            pChildParentParent.replaceChild(div, pChildParent);
                            doIt = false;
                            break;
                        }
                    }
                } else {
                    break;
                }
            }

            // removing all <br...>-Tags
            NodeList brList = document.getElementsByTagName("br");

            while (i < brList.getLength()) {
                Node br = brList.item(i);
                Node parentBrNode = br.getParentNode();
                parentBrNode.removeChild(br);
            }

            // removing everything from script
            NodeList scriptList = document.getElementsByTagName("script");
            while (i < scriptList.getLength()) {
                Node scriptNode = scriptList.item(i);
                Node parentNode = scriptNode.getParentNode();
                parentNode.removeChild(scriptNode);
            }

            // removing all empty <p...>-Tags
            NodeList pList2 = document.getElementsByTagName("p");
            int ccc = 0;
            while (ccc < pList2.getLength()) {
                Node p = pList2.item(ccc);
                NodeList pChilds = p.getChildNodes();

                int kk = 0;

                while (kk < pChilds.getLength()) {
                    Node pChild = pChilds.item(kk);
                    if (pChild.getNodeType() == Node.TEXT_NODE) {
                        String pNodeValue = pChild.getNodeValue();
                        if (pNodeValue == null || StringUtils.isBlank(pNodeValue)
                                || StringUtils.isEmpty(pNodeValue)) {
                            kk++;
                        } else {
                            ccc++;
                            break;
                        }
                    } else {
                        ccc++;
                        break;
                    }
                    if (kk == pChilds.getLength()) {
                        Node parentBrNode = p.getParentNode();
                        parentBrNode.removeChild(p);
                    }
                }
            }

            // removing firstHeading element from document
            Element firstHeadingElement = document.getElementById("firstHeading");
            if (firstHeadingElement != null) {
                CURRENT_OPERATOR_NAME_READ_FROM_RAPIDWIKI = firstHeadingElement.getFirstChild().getNodeValue()
                        .replaceFirst(".*:", "");
                firstHeadingElement.getParentNode().removeChild(firstHeadingElement);
            }

            // setting operator plugin name
            if (opDesc != null && opDesc.getProvider() != null) {
                CURRENT_OPERATOR_PLUGIN_NAME = opDesc.getProvider().getName();
            }

            // removing sitesub element from document
            Element siteSubElement = document.getElementById("siteSub");
            if (siteSubElement != null) {
                siteSubElement.getParentNode().removeChild(siteSubElement);
            }

            // removing contentSub element from document
            Element contentSubElement = document.getElementById("contentSub");
            if (contentSubElement != null) {
                contentSubElement.getParentNode().removeChild(contentSubElement);
            }

            // removing catlinks element from document
            Element catlinksElement = document.getElementById("catlinks");
            if (catlinksElement != null) {
                catlinksElement.getParentNode().removeChild(catlinksElement);
            }

            // removing <a...> element from document, if they are empty
            NodeList aList = document.getElementsByTagName("a");
            if (aList != null) {
                int k = 0;
                while (k < aList.getLength()) {
                    Node a = aList.item(k);
                    Element aElement = (Element) a;
                    if (aElement.getAttribute("class").equals("internal")) {
                        a.getParentNode().removeChild(a);
                    } else {
                        Node aChild = a.getFirstChild();
                        if (aChild != null
                                && (aChild.getNodeValue() != null && aChild.getNodeType() == Node.TEXT_NODE
                                        && StringUtils.isNotBlank(aChild.getNodeValue())
                                        && StringUtils.isNotEmpty(aChild.getNodeValue())
                                        || aChild.getNodeName() != null)) {
                            Element aChildElement = null;
                            if (aChild.getNodeName().startsWith("img")) {
                                aChildElement = (Element) aChild;

                                Element imgElement = document.createElement("img");
                                imgElement.setAttribute("alt", aChildElement.getAttribute("alt"));
                                imgElement.setAttribute("class", aChildElement.getAttribute("class"));
                                imgElement.setAttribute("height", aChildElement.getAttribute("height"));
                                imgElement.setAttribute("src",
                                        WIKI_PREFIX_FOR_IMAGES + aChildElement.getAttribute("src"));
                                imgElement.setAttribute("width", aChildElement.getAttribute("width"));
                                imgElement.setAttribute("border", "1");

                                Node aParent = a.getParentNode();
                                aParent.replaceChild(imgElement, a);
                            } else {
                                k++;
                            }
                        } else {
                            a.getParentNode().removeChild(a);
                        }
                    }
                }
            }

        }
    }
    return document;
}

From source file:DomUtils.java

/**
 * Replace one node with another node./*from  w  w w .  j  a v a 2  s .co  m*/
 * @param newNode New node - added in same location as oldNode.
 * @param oldNode Old node - removed.
 */
public static void replaceNode(Node newNode, Node oldNode) {

    Node parentNode = oldNode.getParentNode();

    if (parentNode == null) {
        System.out.println("Cannot replace node [" + oldNode + "] with [" + newNode + "]. [" + oldNode
                + "] has no parent.");
    } else {
        parentNode.replaceChild(newNode, oldNode);
    }
}

From source file:com.adaptris.util.text.xml.ReplaceNode.java

@Override
public Document merge(Document original, Document newDoc) throws Exception {
    if (StringUtils.isEmpty(getXpathToNode())) {
        throw new Exception("No xpath node configured");
    }//from  www  .ja va2  s.  c o  m
    Document resultDoc = original;
    Node node = createXPath().selectSingleNode(resultDoc, getXpathToNode());
    if (node == null) {
        throw new Exception("Failed to resolve " + getXpathToNode());
    }
    Node parent = node.getParentNode();
    if (parent == null) {
        throw new Exception("Parent of " + getXpathToNode() + " is null");
    }
    Node replacement = resultDoc.importNode(newDoc.getDocumentElement(), true);
    parent.replaceChild(replacement, node);
    return resultDoc;
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected String getSummariesXML(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it/*from  ww w.  j  a  v  a2  s.co m*/
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        Source source = new DOMSource(response);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return "";
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected List<Map<String, Object>> getSummaries(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it//from ww  w .j a  v a 2  s .c om
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();
        nodes = response.getElementsByTagName("DocSum");
        for (int i = 0; i < nodes.getLength(); ++i) {
            Element n = (Element) nodes.item(i);
            Map<String, Object> doc = new HashMap<String, Object>();
            doc.put("id", n.getElementsByTagName("Id").item(0).getTextContent());
            NodeList items = n.getElementsByTagName("Item");
            for (int j = 0; j < items.getLength(); ++j) {
                Element item = (Element) items.item(j);
                if ("List".equals(item.getAttribute("Type"))) {
                    NodeList subitems = item.getElementsByTagName("Item");
                    if (subitems.getLength() > 0) {
                        List<String> values = new ArrayList<String>(subitems.getLength());
                        for (int k = 0; k < subitems.getLength(); ++k) {
                            values.add(subitems.item(k).getTextContent());
                        }
                        doc.put(item.getAttribute("Name"), values);
                    }
                } else {
                    String value = item.getTextContent();
                    if (StringUtils.isNotEmpty(value)) {
                        doc.put(item.getAttribute("Name"), value);
                    }
                }
            }
            result.add(doc);
        }
        return result;
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return Collections.emptyList();
}

From source file:com.photon.phresco.framework.impl.ConfigurationWriter.java

public void updateConfiguration(String envName, String oldConfigName, SettingsInfo settingsInfo)
        throws XPathExpressionException, PhrescoException {
    Node environment = getNode(getXpathEnv(envName).toString());
    if (environment == null) {
        throw new PhrescoException("Environmnet not found to delete the Configuration");
    }//from  w  w w  .  j  av a2  s.c  o m
    Node oldConfigNode = getNode(getXpathConfigByEnv(envName, oldConfigName));
    if (oldConfigNode == null) {
        throw new PhrescoException("Configuration not found to delete");
    }

    Element configElement = createConfigElement(settingsInfo);
    environment.replaceChild(configElement, oldConfigNode);
}