Java Code Examples for org.w3c.dom.Node#removeChild()

The following examples show how to use org.w3c.dom.Node#removeChild() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cougar   File: CommonTypesMangler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void mangleDocument(Node doc) {
	try {
		// First thing to is to get all sharedObject types defined in the IDL
		List<Node> sharedTags = getChildrenWithName(getName(), doc, "sharedTypes");
		for (Node st: sharedTags) {
	         while (st.hasChildNodes()) {
	             doc.appendChild(st.getFirstChild());
             }
	        doc.removeChild(st);
		}
	} catch (ValidationException e) {
		throw new IllegalArgumentException("Unable to mangle document", e);
	}

}
 
Example 2
private static void removeAndAddComment(Document doc, String moduleName) {
	Node extensionNode;
	Node moduleNode;
	moduleNode = doc.getElementsByTagName(moduleName).item(0);
	if (moduleNode != null) {
		extensionNode = moduleNode.getParentNode();
		NamedNodeMap attrs = moduleNode.getAttributes();
		StringBuilder sb = new StringBuilder("<");
		sb.append(moduleName);
		for (int i = 0; i < attrs.getLength(); i++) {
			Attr attribute = (Attr) attrs.item(i);
			sb.append(" " + attribute.getName() + "=\"" + attribute.getValue() + "\"");
		}
		sb.append("/>");

		appendXmlFragment(extensionNode, sb.toString());
		extensionNode.removeChild(moduleNode);
	}
}
 
Example 3
/**
 * remove element
 *
 * @param xpath
 */
public final void removeElement(String xpath)
{
  if(log.isDebugEnabled())
  {
    log.debug("removeElement(String " + xpath + ")");
  }

  List nodes = this.selectNodes(xpath);
  Iterator iterator = nodes.iterator();
  while(iterator.hasNext())
  {
    Node node = (Node) iterator.next();
    Node parent = node.getParentNode();
    parent.removeChild(node);
  }
}
 
Example 4
public void removeContents() {
    Node currentChild = getFirstChild();

    while (currentChild != null) {
        Node temp = currentChild.getNextSibling();
        if (currentChild instanceof javax.xml.soap.Node) {
            ((javax.xml.soap.Node) currentChild).detachNode();
        } else {
            Node parent = currentChild.getParentNode();
            if (parent != null) {
                parent.removeChild(currentChild);
            }

        }
        currentChild = temp;
    }
}
 
Example 5
Source Project: caja   File: DOMTreeBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override protected void detachFromParent(Element element)
        throws SAXException {
    try {
        Node parent = element.getParentNode();
        if (parent != null) {
            parent.removeChild(element);
        }
    } catch (DOMException e) {
        fatal(e);
    }
}
 
Example 6
Source Project: jdk8u-jdk   File: DOMUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes all children nodes from the specified node.
 *
 * @param node the parent node whose children are to be removed
 */
public static void removeAllChildren(Node node) {
    NodeList children = node.getChildNodes();
    for (int i = 0, length = children.getLength(); i < length; i++) {
        node.removeChild(children.item(i));
    }
}
 
Example 7
private static void removeNodes(Node kmerhmessage, NodeList folderNodes) {
   int folderCount = folderNodes.getLength();

   for(int i = 0; i < folderCount; ++i) {
      kmerhmessage.removeChild(folderNodes.item(0));
   }

}
 
Example 8
private static void removeNodes(Node kmerhmessage, NodeList folderNodes) {
   int folderCount = folderNodes.getLength();

   for(int i = 0; i < folderCount; ++i) {
      kmerhmessage.removeChild(folderNodes.item(0));
   }

}
 
Example 9
public static void decryptFolder(SOAPBody soapBody, Crypto crypto) throws TechnicalConnectorException {
   NodeList folderNodes = soapBody.getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedData");
   if (folderNodes.getLength() == 1) {
      Node base64EncryptedDataNode = folderNodes.item(0);
      Node base64EncryptedDataParentNode = base64EncryptedDataNode.getParentNode();

      try {
         NodeList encryptedContent = ((Element)base64EncryptedDataNode).getElementsByTagNameNS("http://www.ehealth.fgov.be/standards/kmehr/schema/v1", "Base64EncryptedValue");
         if (encryptedContent.getLength() == 0 || encryptedContent.getLength() > 1) {
            LOG.debug("Base64EncryptedValue is not a valid content. Nothing to decrypt.");
            return;
         }

         String encryptedData = encryptedContent.item(0).getTextContent();
         byte[] b64decryptedData = Base64.decode(encryptedData.getBytes());
         byte[] decryptedMessage = crypto.unseal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, b64decryptedData).getContentAsByte();
         base64EncryptedDataParentNode.removeChild(base64EncryptedDataNode);
         ConnectorXmlUtils.dump(decryptedMessage);
         NodeList folders = getFolders(decryptedMessage);

         for(int i = 0; i < folders.getLength(); ++i) {
            Element folderElement = (Element)folders.item(i);
            Node folder = base64EncryptedDataParentNode.getOwnerDocument().importNode(folderElement, true);
            base64EncryptedDataParentNode.appendChild(folder);
         }
      } catch (SAXException var13) {
         throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SAX_EXCEPTION, new Object[]{"SAXException when decrypting the SOAP folder", var13});
      } catch (IOException var14) {
         throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_IOEXCEPTION, new Object[]{"IOException when decrypting the SOAP folder", var14});
      }
   } else if (folderNodes.getLength() == 0) {
      LOG.debug("No node with name Base64EncryptedDatafound to decrypt");
   } else if (folderNodes.getLength() > 1) {
      LOG.debug("More then one node with name Base64EncryptedDatafound to decrypt");
   }

}
 
Example 10
protected String migrateBillingResultXml(String billingXml)
        throws Exception {
    Document document = XMLConverter.convertToDocument(billingXml, false);
    NodeList subscriptionCosts = findSubscriptionCost(document);
    for (int i = 0; i < subscriptionCosts.getLength(); i++) {
        Node subscriptionCost = subscriptionCosts.item(i);
        Node parent = subscriptionCost.getParentNode();
        parent.removeChild(subscriptionCost);
    }
    return XMLConverter.convertToString(document, false);
}
 
Example 11
private void overwriteDependencyManagement(Document pom, List<Dependency> dependencies) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("/project/dependencyManagement/dependencies");

    NodeList nodes = (NodeList) expr.evaluate(pom, XPathConstants.NODESET);
    if (nodes.getLength() == 0) {
        throw new IllegalStateException("No dependencies found in the dependencyManagement section of the current pom");
    }

    Node dependenciesSection = nodes.item(0);
    // cleanup the dependency management section
    while (dependenciesSection.hasChildNodes()) {
        Node child = dependenciesSection.getFirstChild();
        dependenciesSection.removeChild(child);
    }

    for (Dependency dep : dependencies) {

        if ("target".equals(dep.getArtifactId())) {
            // skip invalid artifact that somehow gets included
            continue;
        }

        Element dependencyEl = pom.createElement("dependency");

        Element groupIdEl = pom.createElement("groupId");
        groupIdEl.setTextContent(dep.getGroupId());
        dependencyEl.appendChild(groupIdEl);

        Element artifactIdEl = pom.createElement("artifactId");
        artifactIdEl.setTextContent(dep.getArtifactId());
        dependencyEl.appendChild(artifactIdEl);

        Element versionEl = pom.createElement("version");
        versionEl.setTextContent(dep.getVersion());
        dependencyEl.appendChild(versionEl);

        if (!"jar".equals(dep.getType())) {
            Element typeEl = pom.createElement("type");
            typeEl.setTextContent(dep.getType());
            dependencyEl.appendChild(typeEl);
        }

        if (dep.getClassifier() != null) {
            Element classifierEl = pom.createElement("classifier");
            classifierEl.setTextContent(dep.getClassifier());
            dependencyEl.appendChild(classifierEl);
        }

        if (dep.getScope() != null && !"compile".equals(dep.getScope())) {
            Element scopeEl = pom.createElement("scope");
            scopeEl.setTextContent(dep.getScope());
            dependencyEl.appendChild(scopeEl);
        }

        if (dep.getExclusions() != null && !dep.getExclusions().isEmpty()) {

            Element exclsEl = pom.createElement("exclusions");

            for (Exclusion e : dep.getExclusions()) {
                Element exclEl = pom.createElement("exclusion");

                Element groupIdExEl = pom.createElement("groupId");
                groupIdExEl.setTextContent(e.getGroupId());
                exclEl.appendChild(groupIdExEl);

                Element artifactIdExEl = pom.createElement("artifactId");
                artifactIdExEl.setTextContent(e.getArtifactId());
                exclEl.appendChild(artifactIdExEl);

                exclsEl.appendChild(exclEl);
            }

            dependencyEl.appendChild(exclsEl);
        }


        dependenciesSection.appendChild(dependencyEl);
    }


}
 
Example 12
Source Project: hottub   File: RangeImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
Node removeChild(Node parent, Node child) {
    fRemoveChild = child;
    Node n = parent.removeChild(child);
    fRemoveChild = null;
    return n;
}
 
Example 13
/**
 * Replaces the text of the current node and all logically-adjacent text
 * nodes with the specified text. All logically-adjacent text nodes are
 * removed including the current node unless it was the recipient of the
 * replacement text.
 *
 * @param content
 *            The content of the replacing Text node.
 * @return text - The Text node created with the specified content.
 * @since DOM Level 3
 */
public Text replaceWholeText(String content) throws DOMException {

    if (needsSyncData()) {
        synchronizeData();
    }

    //if the content is null
    Node parent = this.getParentNode();
    if (content == null || content.length() == 0) {
        // remove current node
        if (parent != null) { // check if node in the tree
            parent.removeChild(this);
        }
        return null;
    }

    // make sure we can make the replacement
    if (ownerDocument().errorChecking) {
        if (!canModifyPrev(this)) {
            throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
                    DOMMessageFormatter.formatMessage(
                            DOMMessageFormatter.DOM_DOMAIN,
                            "NO_MODIFICATION_ALLOWED_ERR", null));
        }

        // make sure we can make the replacement
        if (!canModifyNext(this)) {
            throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
                    DOMMessageFormatter.formatMessage(
                            DOMMessageFormatter.DOM_DOMAIN,
                            "NO_MODIFICATION_ALLOWED_ERR", null));
        }
    }

    //replace the text node
    Text currentNode = null;
    if (isReadOnly()) {
        Text newNode = this.ownerDocument().createTextNode(content);
        if (parent != null) { // check if node in the tree
            parent.insertBefore(newNode, this);
            parent.removeChild(this);
            currentNode = newNode;
        } else {
            return newNode;
        }
    } else {
        this.setData(content);
        currentNode = this;
    }

    //check logically-adjacent text nodes
    Node prev = currentNode.getPreviousSibling();
    while (prev != null) {
        //If the logically-adjacent next node can be removed
        //remove it. A logically adjacent node can be removed if
        //it is a Text or CDATASection node or an EntityReference with
        //Text and CDATA only children.
        if ((prev.getNodeType() == Node.TEXT_NODE)
                || (prev.getNodeType() == Node.CDATA_SECTION_NODE)
                || (prev.getNodeType() == Node.ENTITY_REFERENCE_NODE && hasTextOnlyChildren(prev))) {
            parent.removeChild(prev);
            prev = currentNode;
        } else {
            break;
        }
        prev = prev.getPreviousSibling();
    }

    //check logically-adjacent text nodes
    Node next = currentNode.getNextSibling();
    while (next != null) {
        //If the logically-adjacent next node can be removed
        //remove it. A logically adjacent node can be removed if
        //it is a Text or CDATASection node or an EntityReference with
        //Text and CDATA only children.
        if ((next.getNodeType() == Node.TEXT_NODE)
                || (next.getNodeType() == Node.CDATA_SECTION_NODE)
                || (next.getNodeType() == Node.ENTITY_REFERENCE_NODE && hasTextOnlyChildren(next))) {
            parent.removeChild(next);
            next = currentNode;
        } else {
            break;
        }
        next = next.getNextSibling();
    }

    return currentNode;
}
 
Example 14
/**
 * Removes the contents of a <code>Node</code>.
 *
 * @param node the <code>Node</code> to clear.
 */
private static void removeContent(Node node) {
    while (node.hasChildNodes()) {
        node.removeChild(node.getFirstChild());
    }
}
 
Example 15
/**
 * Removes the contents of a <code>Node</code>.
 *
 * @param node the <code>Node</code> to clear.
 */
private static void removeContent(Node node) {
    while (node.hasChildNodes()) {
        node.removeChild(node.getFirstChild());
    }
}
 
Example 16
/**
 * Removes the contents of a <code>Node</code>.
 *
 * @param node the <code>Node</code> to clear.
 */
private static void removeContent(Node node) {
    while (node.hasChildNodes()) {
        node.removeChild(node.getFirstChild());
    }
}
 
Example 17
/**
 * Removes the contents of a <code>Node</code>.
 *
 * @param node the <code>Node</code> to clear.
 */
private static void removeContent(Node node) {
    while (node.hasChildNodes()) {
        node.removeChild(node.getFirstChild());
    }
}
 
Example 18
Source Project: jdk8u60   File: TextImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Replaces the text of the current node and all logically-adjacent text
 * nodes with the specified text. All logically-adjacent text nodes are
 * removed including the current node unless it was the recipient of the
 * replacement text.
 *
 * @param content
 *            The content of the replacing Text node.
 * @return text - The Text node created with the specified content.
 * @since DOM Level 3
 */
public Text replaceWholeText(String content) throws DOMException {

    if (needsSyncData()) {
        synchronizeData();
    }

    //if the content is null
    Node parent = this.getParentNode();
    if (content == null || content.length() == 0) {
        // remove current node
        if (parent != null) { // check if node in the tree
            parent.removeChild(this);
        }
        return null;
    }

    // make sure we can make the replacement
    if (ownerDocument().errorChecking) {
        if (!canModifyPrev(this)) {
            throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
                    DOMMessageFormatter.formatMessage(
                            DOMMessageFormatter.DOM_DOMAIN,
                            "NO_MODIFICATION_ALLOWED_ERR", null));
        }

        // make sure we can make the replacement
        if (!canModifyNext(this)) {
            throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
                    DOMMessageFormatter.formatMessage(
                            DOMMessageFormatter.DOM_DOMAIN,
                            "NO_MODIFICATION_ALLOWED_ERR", null));
        }
    }

    //replace the text node
    Text currentNode = null;
    if (isReadOnly()) {
        Text newNode = this.ownerDocument().createTextNode(content);
        if (parent != null) { // check if node in the tree
            parent.insertBefore(newNode, this);
            parent.removeChild(this);
            currentNode = newNode;
        } else {
            return newNode;
        }
    } else {
        this.setData(content);
        currentNode = this;
    }

    //check logically-adjacent text nodes
    Node prev = currentNode.getPreviousSibling();
    while (prev != null) {
        //If the logically-adjacent next node can be removed
        //remove it. A logically adjacent node can be removed if
        //it is a Text or CDATASection node or an EntityReference with
        //Text and CDATA only children.
        if ((prev.getNodeType() == Node.TEXT_NODE)
                || (prev.getNodeType() == Node.CDATA_SECTION_NODE)
                || (prev.getNodeType() == Node.ENTITY_REFERENCE_NODE && hasTextOnlyChildren(prev))) {
            parent.removeChild(prev);
            prev = currentNode;
        } else {
            break;
        }
        prev = prev.getPreviousSibling();
    }

    //check logically-adjacent text nodes
    Node next = currentNode.getNextSibling();
    while (next != null) {
        //If the logically-adjacent next node can be removed
        //remove it. A logically adjacent node can be removed if
        //it is a Text or CDATASection node or an EntityReference with
        //Text and CDATA only children.
        if ((next.getNodeType() == Node.TEXT_NODE)
                || (next.getNodeType() == Node.CDATA_SECTION_NODE)
                || (next.getNodeType() == Node.ENTITY_REFERENCE_NODE && hasTextOnlyChildren(next))) {
            parent.removeChild(next);
            next = currentNode;
        } else {
            break;
        }
        next = next.getNextSibling();
    }

    return currentNode;
}
 
Example 19
Source Project: maven-framework-project   File: ModifyXMLFile.java    License: MIT License 4 votes vote down vote up
public static void main(String argv[]) {
 
   try {
	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	Document doc = docBuilder.parse(ClassLoader.getSystemResourceAsStream("file.xml"));

	// Get the root element
	//Node company = doc.getFirstChild();

	// Get the staff element , it may not working if tag has spaces, or
	// whatever weird characters in front...it's better to use
	// getElementsByTagName() to get it directly.
	// Node staff = company.getFirstChild();

	// Get the staff element by tag name directly
	Node staff = doc.getElementsByTagName("staff").item(0);

	// update staff attribute
	NamedNodeMap attr = staff.getAttributes();
	Node nodeAttr = attr.getNamedItem("id");
	nodeAttr.setTextContent("2");

	// append a new node to staff
	Element age = doc.createElement("age");
	age.appendChild(doc.createTextNode("28"));
	staff.appendChild(age);

	// loop the staff child node
	NodeList list = staff.getChildNodes();

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

          Node node = list.item(i);

	   // get the salary element, and update the value
	   if ("salary".equals(node.getNodeName())) {
		node.setTextContent("2000000");
	   }

                  //remove firstname
	   if ("firstname".equals(node.getNodeName())) {
		staff.removeChild(node);
	   }

	}

	// write the content into xml file
	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	DOMSource source = new DOMSource(doc);
	StreamResult result = new StreamResult(new File("target/file.xml"));
	transformer.transform(source, result);

	System.out.println("Done");

   } catch (ParserConfigurationException pce) {
	pce.printStackTrace();
   } catch (TransformerException tfe) {
	tfe.printStackTrace();
   } catch (IOException ioe) {
	ioe.printStackTrace();
   } catch (SAXException sae) {
	sae.printStackTrace();
   }
}
 
Example 20
Source Project: hottub   File: TextImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Replaces the text of the current node and all logically-adjacent text
 * nodes with the specified text. All logically-adjacent text nodes are
 * removed including the current node unless it was the recipient of the
 * replacement text.
 *
 * @param content
 *            The content of the replacing Text node.
 * @return text - The Text node created with the specified content.
 * @since DOM Level 3
 */
public Text replaceWholeText(String content) throws DOMException {

    if (needsSyncData()) {
        synchronizeData();
    }

    //if the content is null
    Node parent = this.getParentNode();
    if (content == null || content.length() == 0) {
        // remove current node
        if (parent != null) { // check if node in the tree
            parent.removeChild(this);
        }
        return null;
    }

    // make sure we can make the replacement
    if (ownerDocument().errorChecking) {
        if (!canModifyPrev(this)) {
            throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
                    DOMMessageFormatter.formatMessage(
                            DOMMessageFormatter.DOM_DOMAIN,
                            "NO_MODIFICATION_ALLOWED_ERR", null));
        }

        // make sure we can make the replacement
        if (!canModifyNext(this)) {
            throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
                    DOMMessageFormatter.formatMessage(
                            DOMMessageFormatter.DOM_DOMAIN,
                            "NO_MODIFICATION_ALLOWED_ERR", null));
        }
    }

    //replace the text node
    Text currentNode = null;
    if (isReadOnly()) {
        Text newNode = this.ownerDocument().createTextNode(content);
        if (parent != null) { // check if node in the tree
            parent.insertBefore(newNode, this);
            parent.removeChild(this);
            currentNode = newNode;
        } else {
            return newNode;
        }
    } else {
        this.setData(content);
        currentNode = this;
    }

    //check logically-adjacent text nodes
    Node prev = currentNode.getPreviousSibling();
    while (prev != null) {
        //If the logically-adjacent next node can be removed
        //remove it. A logically adjacent node can be removed if
        //it is a Text or CDATASection node or an EntityReference with
        //Text and CDATA only children.
        if ((prev.getNodeType() == Node.TEXT_NODE)
                || (prev.getNodeType() == Node.CDATA_SECTION_NODE)
                || (prev.getNodeType() == Node.ENTITY_REFERENCE_NODE && hasTextOnlyChildren(prev))) {
            parent.removeChild(prev);
            prev = currentNode;
        } else {
            break;
        }
        prev = prev.getPreviousSibling();
    }

    //check logically-adjacent text nodes
    Node next = currentNode.getNextSibling();
    while (next != null) {
        //If the logically-adjacent next node can be removed
        //remove it. A logically adjacent node can be removed if
        //it is a Text or CDATASection node or an EntityReference with
        //Text and CDATA only children.
        if ((next.getNodeType() == Node.TEXT_NODE)
                || (next.getNodeType() == Node.CDATA_SECTION_NODE)
                || (next.getNodeType() == Node.ENTITY_REFERENCE_NODE && hasTextOnlyChildren(next))) {
            parent.removeChild(next);
            next = currentNode;
        } else {
            break;
        }
        next = next.getNextSibling();
    }

    return currentNode;
}