Example usage for org.w3c.dom Document removeChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Document 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:Main.java

/**
 * Clones a document object.//from   www  .j a v  a2  s  .c o m
 *
 * @param doc The document to be cloned.
 * @return The new document object that contains the same data as the original document.
 * @throws TransformerException Thrown if the document can't be
 */
public static Document cloneDocument(final Document doc) throws TransformerException {
    final Node rootNode = doc.getDocumentElement();

    // Copy the doctype and xml version type data
    final TransformerFactory tfactory = TransformerFactory.newInstance();
    final Transformer tx = tfactory.newTransformer();
    final DOMSource source = new DOMSource(doc);
    final DOMResult result = new DOMResult();
    tx.transform(source, result);

    // Copy the actual content into the new document
    final Document copy = (Document) result.getNode();
    copy.removeChild(copy.getDocumentElement());
    final Node copyRootNode = copy.importNode(rootNode, true);
    copy.appendChild(copyRootNode);

    return copy;
}

From source file:Main.java

public static Document addRoot(Document dataDoc, String elementName) {
    Element oldRoot = dataDoc.getDocumentElement();
    Element newRoot = dataDoc.createElement(elementName);
    dataDoc.removeChild(oldRoot);
    newRoot.appendChild(oldRoot);/*from   w  w w. j  a  v  a2 s  . com*/
    dataDoc.appendChild(newRoot);
    return dataDoc;
}

From source file:Main.java

/**
 * Clears all childnodes in document/*from  www.  ja v  a 2  s .c o  m*/
 */
public static void clearDocument(Document document) {
    NodeList nodeList = document.getChildNodes();
    if (nodeList == null) {
        return;
    }
    int len = nodeList.getLength();
    for (int i = 0; i < len; i++) {
        document.removeChild(nodeList.item(i));
    }
}

From source file:Main.java

/**
 * Converts the document from namespace-qualified form into unqualified form by removing all 
 * namespace information./*from   ww  w .j  a  v a2  s .c  o m*/
 * 
 * @param document the document to convert
 */

public static void convertFromNamespaceForm(final Document document) {
    final Element oldRootElement = document.getDocumentElement();

    if (oldRootElement != null) {
        final Node nodeAfterRootElement = oldRootElement.getNextSibling();
        final Node newRootElement = convertFromNamespaceForm(oldRootElement);
        document.removeChild(oldRootElement);
        document.insertBefore(newRootElement, nodeAfterRootElement);
    }
}

From source file:Main.java

/**
 * Try to normalize a document by removing nonsignificant whitespace.
 *
 * @see "#62006"/*from  w  w  w.  jav a2s.co  m*/
 */
private static Document normalize(Document orig) throws IOException {
    DocumentBuilder builder = null;
    DocumentBuilderFactory factory = getFactory(false, false);
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException("Cannot create parser satisfying configuration parameters: " + e, e); //NOI18N
    }

    DocumentType doctype = null;
    NodeList nl = orig.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i) instanceof DocumentType) {
            // We cannot import DocumentType's, so we need to manually copy it.
            doctype = (DocumentType) nl.item(i);
        }
    }
    Document doc;
    if (doctype != null) {
        doc = builder.getDOMImplementation().createDocument(orig.getDocumentElement().getNamespaceURI(),
                orig.getDocumentElement().getTagName(),
                builder.getDOMImplementation().createDocumentType(orig.getDoctype().getName(),
                        orig.getDoctype().getPublicId(), orig.getDoctype().getSystemId()));
        // XXX what about entity decls inside the DOCTYPE?
        doc.removeChild(doc.getDocumentElement());
    } else {
        doc = builder.newDocument();
    }
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (!(node instanceof DocumentType)) {
            try {
                doc.appendChild(doc.importNode(node, true));
            } catch (DOMException x) {
                // Thrown in NB-Core-Build #2896 & 2898 inside GeneratedFilesHelper.applyBuildExtensions
                throw new IOException("Could not import or append " + node + " of " + node.getClass(), x);
            }
        }
    }
    doc.normalize();
    nl = doc.getElementsByTagName("*"); // NOI18N
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        removeXmlBase(e);
        NodeList nl2 = e.getChildNodes();
        for (int j = 0; j < nl2.getLength(); j++) {
            Node n = nl2.item(j);
            if (n instanceof Text && ((Text) n).getNodeValue().trim().length() == 0) {
                e.removeChild(n);
                j--; // since list is dynamic
            }
        }
    }
    return doc;
}

From source file:no.difi.sdp.client.asice.signature.CreateSignature.java

private void wrapSignatureInXADeSEnvelope(final Document document) {
    Node signatureElement = document.removeChild(document.getDocumentElement());
    Element xadesElement = document.createElementNS(asicNamespace, "XAdESSignatures");
    xadesElement.appendChild(signatureElement);
    document.appendChild(xadesElement);/* www . j a  va2s. c  om*/
}

From source file:be.fedict.eid.pkira.xkmsws.util.XMLMarshallingUtil.java

public void removeSoapHeaders(Document document) {
    NodeList bodyNodes = document.getElementsByTagNameNS(NAMESPACE_SOAP, "Body");
    if (bodyNodes != null && bodyNodes.getLength() == 1) {
        Element body = (Element) bodyNodes.item(0);

        NodeList children = body.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i) instanceof Element) {
                document.removeChild(document.getDocumentElement());
                document.appendChild(children.item(i));
                break;
            }/*from ww w .j  a  va 2  s  .  c om*/
        }
    }
}

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

public static Element createRootElement(Document doc, String name) {

    if (name == null) {
        throw new XMLToolException("Root element name cannot be null!");
    } else if (name.trim().length() == 0) {
        throw new XMLToolException("Root element name has to contain at least one character!");
    }//w  w  w. j a v a  2s. c om

    // remove old root
    NodeList nodes = doc.getChildNodes();
    Node[] element = filterNodes(nodes, Node.ELEMENT_NODE);
    for (int i = 0; i < element.length; i++) {
        doc.removeChild(element[i]);
    }

    // create and append the new root
    Element root = doc.createElement(name);
    doc.appendChild(root);

    return root;
}

From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java

/**
 * Addapts bugzilla XML document for transformations
 * //from  ww  w. java 2 s  . c o m
 * @param docBugzilla
 */
private void cleanBugzillaDocument(final Document docBugzilla) {

    // quitamos el DTD
    final Node docType = docBugzilla.getDoctype();
    docBugzilla.removeChild(docType);

    // ponemos el ttulo
    final Element title = docBugzilla.createElement(ELEMENT_TITLE);
    title.appendChild(docBugzilla.createTextNode(this.project.getName()));
    docBugzilla.getDocumentElement().appendChild(title);

    // ponemos los atributos de version para la ordenacin
    final NodeList target_milestones = docBugzilla.getElementsByTagName(ELEMENT_TARGET_MILESTONE);
    for (int i = 0; i < target_milestones.getLength(); i++) {
        final Element target_milestone = (Element) target_milestones.item(i);
        final String version = target_milestone.getTextContent();
        final String[] versions = version.split("\\.");
        // solo tenemos en cuenta las dos primeras
        // (ej. para version="1.23" tenemos la version1="1" y version2="23";
        // y para version="1.23.3" se tiene lo mismo)
        String version1 = "";
        if (versions.length > 0) {
            version1 = versions[0];
        }
        String version2 = "";
        if (versions.length >= 2) {
            version2 = versions[1];
        }
        target_milestone.setAttribute(ATTRIBUTE_VERSION1, version1);
        target_milestone.setAttribute(ATTRIBUTE_VERSION2, version2);
    }

    // si hay que ajustar los desarrolladores lo procesamos
    if (this.fitDevelopers) {
        final NodeList assigned_tos = docBugzilla.getElementsByTagName(ELEMENT_ASSIGNED_TO);
        for (int i = 0; i < assigned_tos.getLength(); i++) {
            final Element assigned_to = (Element) assigned_tos.item(i);
            String developer = assigned_to.getTextContent();
            final int index = developer.indexOf("@");
            if (index != -1) {
                developer = developer.substring(0, index);
            }
            // quitamos el texto
            final NodeList childs = assigned_to.getChildNodes();
            for (int j = 0; j < childs.getLength(); j++) {
                final Node child = childs.item(j);
                assigned_to.removeChild(child);
                // disminuimos j debido a que tambin se quita del nodelist
                j--;
            }
            assigned_to.appendChild(docBugzilla.createTextNode(developer));
        }
    }

    // eliminamos los nodos que no son necesarios
    final String[] nodes2Clean = { "creation_ts", "reporter_accessible", "cclist_accessible",
            "classification_id", "classification", "product", "component", "version", "rep_platform", "op_sys",
            "bug_status", "resolution", "priority", "everconfirmed", "estimated_time", "remaining_time",
            "actual_time", "who", "thetext" };
    for (final String node2clean : nodes2Clean) {
        this.removeNodes(docBugzilla.getElementsByTagName(node2clean));
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Transform into formatted XML.//from  w  w w  .j  a  v a 2  s . c o m
 */
private String getFormattedXml(Node node) {
    Document document = node.getOwnerDocument().getImplementation().createDocument("", "fake", null);
    Element copy = (Element) document.importNode(node, true);
    document.importNode(node, false);
    document.removeChild(document.getDocumentElement());
    document.appendChild(copy);
    DOMImplementation domImpl = document.getImplementation();
    DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
    LSSerializer serializer = domImplLs.createLSSerializer();
    serializer.getDomConfig().setParameter("format-pretty-print", true);
    return serializer.writeToString(document);
}