Example usage for org.w3c.dom Node removeChild

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

Introduction

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

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:com.photon.phresco.framework.commons.QualityUtil.java

private static Node removeAllChilds(Node hashTree) {
    NodeList childNodes = hashTree.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        hashTree.removeChild(childNodes.item(i));
    }/*from  w  ww .j  ava2  s .  c  om*/
    return hashTree;
}

From source file:Main.java

/**
 * Remove any whitespace text nodes from the DOM. Calling this before saving
 * a formatted document will fix the formatting indentation of elements
 * loaded from a different document./*from  ww w  .j  av a 2  s.  co  m*/
 * 
 * @param node
 *            Node to remove whitespace nodes from
 * @param deep
 *            Should this method recurse into the node's children?
 */
public static void removeWhitespace(Node node, boolean deep) {
    NodeList children = node.getChildNodes();
    int length = children.getLength();
    for (int i = 0; i < length; i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.TEXT_NODE && length > 1) {
            Node previous = child.getPreviousSibling();
            Node next = child.getNextSibling();
            if ((previous == null || previous.getNodeType() == Node.ELEMENT_NODE
                    || previous.getNodeType() == Node.COMMENT_NODE)
                    && (next == null || next.getNodeType() == Node.ELEMENT_NODE
                            || next.getNodeType() == Node.COMMENT_NODE)) {
                String content = child.getTextContent();
                if (content.matches("\\s*")) //$NON-NLS-1$
                {
                    node.removeChild(child);
                    i--;
                    length--;
                }
            }
        } else if (deep && child.getNodeType() == Node.ELEMENT_NODE) {
            removeWhitespace(child, deep);
        }
    }
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * modify scoEntryItem in scoEntryContent, move lom from scoEntryItem
 * /*from  w  w  w  .  jav a2s .  c o m*/
 * @param nodes
 * @throws Exception
 */
private static void walkingthrough(Node nodes, org.w3c.dom.Document document) throws Exception {

    changeScoEntry(nodes, document);

    int length = nodes.getChildNodes().getLength();
    for (int i = 0; i < length; i++) {
        Node node = nodes.getChildNodes().item(i);

        changeScoEntry(node, document);

        if (node.getNodeName().equals("scoEntryItem")) {
            // the lom children must linked to the parent child (scoEntry)
            int lengthlom = node.getChildNodes().getLength();
            for (int lom = 0; lom < lengthlom; lom++) {
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("lom:lom")) {
                    // clone the node..
                    Node cloneLom = node.getChildNodes().item(lom).cloneNode(true);
                    // first of all I remove it
                    Node lomnode = node.getChildNodes().item(lom);
                    Node father = lomnode.getParentNode();
                    Node grandf = father.getParentNode();
                    father.removeChild(lomnode);
                    // then I add it to the new parent..
                    grandf.insertBefore(cloneLom, father);
                }

                // for each dmRef open the DM and read the real data module
                // content to be show in the lesson
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("dmRef")) {
                    String filename = resourcepack + "\\" + gettingDmfilename(node.getChildNodes().item(lom))
                            + ".xml";
                    if (new File(filename).exists()) {
                        // if the data module is a scoContent will copy each
                        // dmref in the scoEntry
                        org.w3c.dom.Document dm41 = getDoc(new File(filename));

                        if (processXPathSingleNode("dmodule/content/scoContent", dm41) != null)
                            ;
                        {
                            NodeList dmre = processXPath("/dmodule/content/scoContent/trainingStep/dmRef",
                                    dm41);
                            Node father = node.getChildNodes().item(lom).getParentNode();
                            father.removeChild(node.getChildNodes().item(lom));
                            // remove the reference to Scocontent and
                            // replace it with the dm inside
                            for (int nodi = 0; nodi < dmre.getLength(); nodi++) {
                                Node cloneref = dmre.item(nodi).cloneNode(true);
                                document.adoptNode(cloneref);
                                father.appendChild(cloneref);
                            }

                        }
                    }

                }

            }

            // rename scoEntryItem in scoEntry
            node = changeNodename(node, document, "scoEntryContent");
        }
        walkingthrough(node, document);
    }
}

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

/**
 * /*from ww w  . j a  v a2  s .  com*/
 * @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

/**
 * Remove all child nodes from the supplied node.
 * @param node to be "cleared"./*from ww w.jav  a 2s  .  c  o m*/
 */
public static void removeChildren(Node node) {

    NodeList children = node.getChildNodes();
    int nodeCount = children.getLength();

    for (int i = 0; i < nodeCount; i++) {
        node.removeChild(children.item(0));
    }
}

From source file:Main.java

/**
 * Removes all the children of a given Node
 *
 * @param node the Node whose children is to be removed
 * @return Node after the children removed
 *///ww  w .ja  va 2s . co m

public static Node removeChildren(Node node)

{

    /*
            
    System.out.println(" Node whose children are to be removed:" + node.getNodeName() + 
            
                            ":Type:" + node.getNodeType() + ":value:" + node.getNodeValue());
            
     */

    // Currently remove children of only Element Nodes

    if (node.getNodeType() == Node.ELEMENT_NODE)

    {

        NodeList children = node.getChildNodes();

        //System.out.println("***** XMLUTIL....removeChildren....# of children are " + children.getLength());

        for (int i = 0; i < children.getLength(); i++)

        {

            Node child = children.item(i);

            /*
                    
            System.out.println("Child Name:" + child.getNodeName() + 
                    
                                ":Type:" + child.getNodeType() + " value:" + child.getNodeValue() + ":i= " + i);
                    
             */

            Node temp = node.removeChild(child);

            /*
                    
            System.out.println("Removed Name:" + temp.getNodeName() + 
                    
                            ":Type:" + temp.getNodeType() + " value:" + temp.getNodeValue() + ":i= " + i);
                    
             */

            i--;

        }

    }

    return node;

}

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

/**
 * Moves a child the given index in a nodelist for a given number of steps.
 *
 * @param nodelist the nodelist to work on. if the nodelist is empty, nothing is done
 * @param index    index pointing to the child to move.  if the index is not in the list range nothing is done.
 * @param step     the amount of slots to move the child.  if step is negative the child is moved up (towards the list
 *                 start), if it is positive it is moved down (towards the list end). if the step is zero nothing is done.
 *///w  ww.  ja v  a2  s . c o  m
public static void moveChild(NodeList nodelist, int index, int step) {
    if ((nodelist == null) || (nodelist.getLength() == 0)) {
        return;
    }

    if ((index >= nodelist.getLength()) || (index < 0)) {
        return;
    }

    if (step == 0) {
        return;
    }

    Node parent = nodelist.item(0).getParentNode();
    Node deletedElt = parent.removeChild(nodelist.item(index));

    if ((index + step) == (nodelist.getLength() - 1)) {
        parent.appendChild(deletedElt);
    } else {
        // SURE? it seems that after a removeChild the indices of the nodes
        // in the nodelist seem not to change.  Checking the DOM spec the
        // nodelist is live, but this seems not to be true for index changes
        // is this a bug, or correct?
        // Due to this behaviour the following seperation betweem step forward
        // and backward is necessary.
        if (step < 0) {
            parent.insertBefore(deletedElt, nodelist.item(index + step));
        } else {
            parent.insertBefore(deletedElt, nodelist.item(index + step + 1));
        }
    }
}

From source file:fi.vrk.xroad.catalog.lister.WsdlCdataInterceptor.java

@Override
public boolean handleResponse(MessageContext messageContext, Object o) throws Exception {

    WebServiceMessage response = messageContext.getResponse();

    SaajSoapMessage saajSoapMessage = (SaajSoapMessage) response;
    SOAPMessage soapMessage = saajSoapMessage.getSaajMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPBody body = envelope.getBody();
    Iterator responses = body//from ww  w. j  a  v  a 2 s.co  m
            .getChildElements(new QName("http://xroad.vrk.fi/xroad-catalog-lister", "GetWsdlResponse"));
    while (responses.hasNext()) {
        Node wsdlResponse = (Node) responses.next();
        NodeList children = wsdlResponse.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getLocalName().equals("wsdl")) {
                CDATASection cdat = soapPart.createCDATASection(child.getFirstChild().getNodeValue());
                child.removeChild(child.getFirstChild());
                child.appendChild(cdat);
            }
        }
    }
    return true;
}

From source file:DomUtils.java

/**
 * Replace one node with a list of nodes.
 * @param newNodes New nodes - added in same location as oldNode.
 * @param oldNode Old node - removed.//w ww  . jav  a2 s  .  c o  m
 * @param clone Clone Nodelist Nodes.
 */
public static void replaceNode(NodeList newNodes, Node oldNode, boolean clone) {

    Node parentNode = oldNode.getParentNode();

    if (parentNode == null) {
        System.out
                .println("Cannot replace [" + oldNode + "] with a NodeList. [" + oldNode + "] has no parent.");
        return;
    }

    int nodeCount = newNodes.getLength();
    List nodeList = DomUtils.copyNodeList(newNodes);

    if (nodeCount == 0) {
        if (!(parentNode instanceof Document)) {
            parentNode.removeChild(oldNode);
        }
        return;
    }

    if (parentNode instanceof Document) {
        List elements = DomUtils.getElements(newNodes, "*", null);

        if (!elements.isEmpty()) {
            System.out.println(
                    "Request to replace the Document root node with a 1+ in length NodeList.  Replacing root node with the first element node from the NodeList.");
            parentNode.removeChild(oldNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            System.out.println(
                    "Cannot replace document root element with a NodeList that doesn't contain an element node.");
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            if (clone) {
                parentNode.insertBefore(((Node) nodeList.get(i)).cloneNode(true), oldNode);
            } else {
                parentNode.insertBefore((Node) nodeList.get(i), oldNode);
            }
        }
        parentNode.removeChild(oldNode);
    }
}