Example usage for org.w3c.dom Element removeChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Element 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.enonic.esl.xml.XMLTool.java

/**
 * Removes a child element from a parent element, and returns the next element to the removed one.
 *
 * @param parent The parent element to the child to be removed.
 * @param child  The child element to remove.
 * @return The next element to the removed child.
 *//*from  w  w w  .  java  2s  .  c  o  m*/
public static Element removeChildFromParent(Element parent, Element child) {

    Element previousChild = (Element) child.getPreviousSibling();

    // If the child to remove is the first child
    if (previousChild == null) {
        parent.removeChild(child);
        // Return the first child as the next child
        return (Element) parent.getFirstChild();
    }
    // If the child is not the first child
    else {
        parent.removeChild(child);
        return (Element) previousChild.getNextSibling();
    }
}

From source file:cz.incad.kramerius.service.replication.ExternalReferencesFormat.java

private void changeDatastreamVersion(Document document, Element datastream, Element version, URL url)
        throws IOException {
    InputStream is = null;/*from   w  w  w  . j a v  a 2 s. c om*/
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        URLConnection urlConnection = url.openConnection();
        is = urlConnection.getInputStream();
        IOUtils.copyStreams(is, bos);
        version.setAttribute("SIZE", "" + bos.size());
        version.removeChild(XMLUtils.findElement(version, "contentLocation", version.getNamespaceURI()));
        Element binaryContent = document.createElementNS(version.getNamespaceURI(), "binaryContent");
        document.adoptNode(binaryContent);
        binaryContent.setTextContent(new String(Base64.encodeBase64(bos.toByteArray())));
        version.appendChild(binaryContent);

        datastream.setAttribute("CONTROL_GROUP", "M");

    } finally {
        IOUtils.tryClose(is);
    }
}

From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java

public static void replacePidsInDOM(Element docE) {
    String[] apiReplace = KConfiguration.getInstance().getAPIPIDReplace();
    for (String k : apiReplace) {
        if (k.equals("PID"))
            continue; // already replaced
        Element foundElm = findSolrElement(docE, k);
        if (foundElm != null) {

            if (foundElm.getNodeName().equals("str")) {
                String value = SOLRUtils.value(foundElm.getTextContent(), String.class);
                if (value != null && (value.indexOf("/@") > 0)) {
                    value = value.replace("/@", "@");
                    foundElm.setTextContent(value);
                }//from  w w  w.  j a v  a 2s  . com
            } else if (foundElm.getNodeName().equals("arr")) {
                List<String> array = SOLRUtils.array(docE, k, String.class);
                List<String> newArray = new ArrayList<String>();
                for (String value : array) {
                    value = value.replace("/@", "@");
                    newArray.add(value);
                }

                docE.removeChild(foundElm);
                Element newArrElm = SOLRUtils.arr(foundElm.getOwnerDocument(), k, newArray);
                docE.appendChild(newArrElm);
            } else {
                LOGGER.warning("skipping object type '" + foundElm.getNodeName() + "'");
            }

        }
    }

}

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentTrimmer.java

public void processElement(final Element element) throws IOException {
    final NodeList nodeList = element.getChildNodes();
    for (int index = nodeList.getLength() - 1; index >= 0; index--) {
        final Node node = nodeList.item(index);
        if (node instanceof Element) {
            final Element lookup = (Element) node;

            if ("script".equals(lookup.getTagName())) {
                // REMOVE script tag.
                element.removeChild(node);
                continue;
            }/*from w ww  .j a va2 s  .  com*/

            if ("noscript".equals(lookup.getTagName())) {
                // REMOVE noscript tag.
                element.removeChild(node);
                continue;
            }

            if ("iframe".equals(lookup.getTagName())) {
                final NamedNodeMap nnm = lookup.getAttributes();
                for (int indexNnm = 0; indexNnm < nnm.getLength(); indexNnm++) {
                    final Attr attr = (Attr) nnm.item(indexNnm);

                    // System.out.println(" " + attr.getName() + " [" +
                    // attr.getValue() + "]");
                    if ("style".equals(attr.getName())) {
                        final String value = attr.getValue().replaceAll(" ", "");
                        if (value.indexOf("display:none") >= 0) {
                            // REMOVE iframe tag which is display:none
                            // style..
                            element.removeChild(node);
                            continue;
                        }
                    }
                }
            }

            processElement(lookup);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.web.templatemodels.customlistview.CustomListViewConfigFile.java

private void removeChildElements(Element element, String tagName) {
    /*/*  ww  w  .ja  va  2  s  . c om*/
     * When we remove a child from the element, it disappears from the
     * NodeList. We process the NodeList in reverse order, so we won't be
     * disturbed by nodes disappearing off the end. Strange.
     */
    NodeList doomed = element.getElementsByTagName(tagName);
    for (int i = doomed.getLength() - 1; i >= 0; i--) {
        element.removeChild(doomed.item(i));
    }
}

From source file:org.gvnix.dynamic.configuration.roo.addon.PomManagerImpl.java

/**
 * Write a configurations into POM profile.
 * //from w  w w . ja v a 2 s . co m
 * @param doc Pom document
 * @param dynConf
 * @return New configuration element
 */
protected Element exportConfiguration(Document doc, DynConfiguration dynConf) {

    Element root = doc.getDocumentElement();

    // <project>
    // <profiles>
    // <profile>
    // <id>test</id>
    // <activation>
    // <activeByDefault>true</activeByDefault>
    // </activation>
    // </profile>
    // </profiles>
    // </project>

    // Profiles section: find or create if not exists
    Element profs = XmlUtils.findFirstElement("/project/profiles", root);
    if (profs == null) {

        profs = doc.createElement("profiles");
        root.appendChild(profs);
    }

    // Remove profile if already exists
    Element prof = XmlUtils.findFirstElement("profile/id[text()='" + dynConf.getName() + "']/..", profs);
    if (prof != null) {

        profs.removeChild(prof);
    }

    // Create a profile section for this dynamic configuration
    prof = doc.createElement("profile");
    profs.appendChild(prof);

    // Create an identifier for profile
    Element id = doc.createElement("id");
    id.setTextContent(dynConf.getName());
    prof.appendChild(id);

    // If dynamic configuration is active: profile active by default
    if (dynConf.isActive()) {

        // Create an activation section
        Element activation = doc.createElement("activation");
        prof.appendChild(activation);

        Element active = doc.createElement("activeByDefault");
        active.setTextContent("true");
        activation.appendChild(active);
    }

    return prof;
}

From source file:org.gvnix.dynamic.configuration.roo.addon.ConfigurationsImpl.java

/**
 * {@inheritDoc}//from w w  w.  jav  a  2  s. co  m
 */
public void deleteConfiguration(Element conf) {

    // Remove configuration element and their child component elements
    List<Element> comps = XmlUtils.findElements(COMPONENT_ELEMENT_NAME, conf);
    for (Element comp : comps) {
        conf.removeChild(comp);
    }
    conf.getParentNode().removeChild(conf);

    // If active configuration, remove the reference on configuration file
    Element activeConf = isActiveConfiguration(conf);
    if (activeConf != null) {
        activeConf.setTextContent("");
    }

    // Update the configuration file
    saveConfiguration(conf);
}

From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java

public Data transform(Data data, XMLCryptoContext context) throws TransformException {
    LOG.debug("transform(data,context)");
    LOG.debug("data java type: " + data.getClass().getName());
    OctetStreamData octetStreamData = (OctetStreamData) data;
    LOG.debug("URI: " + octetStreamData.getURI());
    InputStream octetStream = octetStreamData.getOctetStream();
    Document relationshipsDocument;
    try {// ww w  . j  a v  a  2s. c om
        relationshipsDocument = loadDocument(octetStream);
    } catch (Exception e) {
        throw new TransformException(e.getMessage(), e);
    }
    try {
        LOG.debug("relationships document: " + toString(relationshipsDocument));
    } catch (TransformerException e) {
        throw new TransformException(e.getMessage(), e);
    }
    Element nsElement = relationshipsDocument.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
            "http://schemas.openxmlformats.org/package/2006/relationships");
    Element relationshipsElement = relationshipsDocument.getDocumentElement();
    NodeList childNodes = relationshipsElement.getChildNodes();
    for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) {
        Node childNode = childNodes.item(nodeIdx);
        if (Node.ELEMENT_NODE != childNode.getNodeType()) {
            LOG.debug("removing node");
            relationshipsElement.removeChild(childNode);
            nodeIdx--;
            continue;
        }
        Element childElement = (Element) childNode;
        String idAttribute = childElement.getAttribute("Id");
        String typeAttribute = childElement.getAttribute("Type");
        LOG.debug("Relationship id attribute: " + idAttribute);
        LOG.debug("Relationship type attribute: " + typeAttribute);
        if (false == this.sourceIds.contains(idAttribute)
                && false == this.sourceTypes.contains(typeAttribute)) {
            LOG.debug("removing Relationship element: " + idAttribute);
            relationshipsElement.removeChild(childNode);
            nodeIdx--;
        }
        /*
         * See: ISO/IEC 29500-2:2008(E) - 13.2.4.24 Relationships Transform
         * Algorithm.
         */
        if (null == childElement.getAttributeNode("TargetMode")) {
            childElement.setAttribute("TargetMode", "Internal");
        }
    }
    LOG.debug("# Relationship elements: " + relationshipsElement.getElementsByTagName("*").getLength());
    sortRelationshipElements(relationshipsElement);
    try {
        return toOctetStreamData(relationshipsDocument);
    } catch (TransformerException e) {
        throw new TransformException(e.getMessage(), e);
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

public static void removeChildNodes(Element root, boolean keepAttributeNodes) {

    if (root == null) {
        return;//  w  ww.  j  a  va 2s  .  c om
    }

    NodeList nodeList = root.getChildNodes();
    for (int i = 0; i < nodeList.getLength();) {
        Node n = nodeList.item(i);
        if ((!keepAttributeNodes && n.getNodeType() == Node.ATTRIBUTE_NODE)
                || n.getNodeType() != Node.ATTRIBUTE_NODE) {
            root.removeChild(n);
        } else {
            i++;
        }
    }
}

From source file:org.dozer.eclipse.plugin.editorpage.DozerModelManager.java

private Binding bindValue(IDOMDocument document, final IObservableValue observedElement,
        IObservableValue observedView) {
    IObservableValue observedValue = SSEDOMObservables.observeDetailCharacterData(Realm.getDefault(),
            observedElement);//from  www.  j  ava2  s.c  om

    //do the binding
    return dataBindingContext.bindValue(observedView, observedValue,
            new UpdateValueStrategy().setConverter(new Converter(String.class, String.class) {

                public Object convert(Object fromObject) {
                    Element element = (Element) ((IObserving) observedElement).getObserved();

                    //remove node if value is set to empty
                    if ("".equals(fromObject.toString()) && element != null) {
                        Element parentNode = (Element) element.getParentNode();
                        parentNode.removeChild(element);

                        //Remove the parent node also, if this was the last child
                        Element[] remainingElements = DOMUtils.getElements(parentNode);
                        if (remainingElements == null || remainingElements.length == 0) {
                            parentNode.getParentNode().removeChild(parentNode);
                        }

                        return null;
                    }

                    return fromObject;
                }

            }).setBeforeSetValidator(new IValidator() {

                public IStatus validate(Object value) {
                    //dont set value if it is null. Thus no parent node gets created.
                    //The parent node has been deleted in converter
                    return value == null ? Status.CANCEL_STATUS : Status.OK_STATUS;
                }

            }), null);
}