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:org.dhatim.xml.DomUtils.java

/**
 * Insert the supplied node before the supplied reference node (refNode).
 * @param newNode Node to be inserted.// w ww .  j  av  a 2 s  . c  om
 * @param refNode Reference node before which the supplied nodes should
 * be inserted.
 */
public static void insertBefore(Node newNode, Node refNode) {
    AssertArgument.isNotNull(newNode, "newNode");
    AssertArgument.isNotNull(refNode, "refNode");

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        logger.debug(
                "Cannot insert [" + newNode + "] before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

    if (parentNode instanceof Document && newNode.getNodeType() == Node.ELEMENT_NODE) {
        logger.debug(
                "Request to insert an element before the Document root node.  This is not allowed.  Replacing the Document root with the new Node.");
        parentNode.removeChild(refNode);
        parentNode.appendChild(newNode);
    } else {
        parentNode.insertBefore(newNode, refNode);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Insert the supplied nodes before the supplied reference node (refNode).
 * @param newNodes Nodes to be inserted.
 * @param refNode Reference node before which the supplied nodes should
 * be inserted.//from ww w.j a v  a  2  s .  c  om
 */
public static void insertBefore(NodeList newNodes, Node refNode) {
    AssertArgument.isNotNull(newNodes, "newNodes");
    AssertArgument.isNotNull(refNode, "refNode");

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        logger.debug("Cannot insert a NodeList before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

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

    if (nodeCount == 0) {
        return;
    }

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

        if (!elements.isEmpty()) {
            logger.debug(
                    "Request to insert a NodeList before the Document root node.  Will replace the root element with the 1st element node from the NodeList.");
            parentNode.removeChild(refNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            logger.debug(
                    "Cannot insert beforen the document root element from a NodeList that doesn't contain an element node.");
        }

        for (int i = 0; i < nodeCount; i++) {
            Node node = (Node) nodeList.get(i);
            if (node.getNodeType() != Node.ELEMENT_NODE) {
                System.out.println("****" + node);
                parentNode.insertBefore(node, refNode);
            }
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            parentNode.insertBefore((Node) nodeList.get(i), refNode);
        }
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Remove the supplied element from its containing document.
 * <p/>// w  w  w .ja  v  a2 s. co  m
 * Tries to manage scenarios where a request is made to remove the root element.
 * Cannot remove the root element in any of the following situations:
 * <ul>
 *    <li>"keepChildren" parameter is false.</li>
 *    <li>root element is empty of {@link Node#ELEMENT_NODE} nodes.</li>
 * </ul>
 * @param element Element to be removed.
 * @param keepChildren Keep child content.
 */
public static void removeElement(Element element, boolean keepChildren) {
    AssertArgument.isNotNull(element, "element");

    Node parent = element.getParentNode();
    if (parent == null) {
        logger.debug("Cannot remove element [" + element + "]. [" + element + "] has no parent.");
        return;
    }

    NodeList children = element.getChildNodes();

    if (parent instanceof Document) {
        List childElements = null;

        if (!keepChildren) {
            logger.debug("Cannot remove document root element [" + DomUtils.getName(element)
                    + "] without keeping child content.");
        } else {
            if (children != null && children.getLength() > 0) {
                childElements = DomUtils.getElements(element, "*", null);
            }

            if (childElements != null && !childElements.isEmpty()) {
                parent.removeChild(element);
                parent.appendChild((Element) childElements.get(0));
            } else {
                logger.debug("Cannot remove empty document root element [" + DomUtils.getName(element) + "].");
            }
        }
    } else {
        if (keepChildren && children != null) {
            DomUtils.insertBefore(children, element);
        }
        parent.removeChild(element);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Remove all child nodes from the supplied node.
 * @param node to be "cleared"./*from w ww  .  ja  va2  s.  c  o m*/
 */
public static void removeChildren(Node node) {
    AssertArgument.isNotNull(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:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 * @param method//from w ww  .j  a  va  2  s  .co m
 */
private void removeMethod(GiMethod method) {
    Element element = method.getElement();

    Node parent = element.getParentNode();
    if (parent != null) {
        parent.removeChild(element);
    }
}

From source file:org.docx4j.openpackaging.parts.XmlPart.java

/**
 * Set the value of the node referenced in the xpath expression.
 * //from  w ww .  ja va  2 s .  c o m
 * @param xpath
 * @param value
 * @param prefixMappings a string such as "xmlns:ns0='http://schemas.medchart'"
 * @return
 * @throws Docx4JException
 */
public boolean setNodeValueAtXPath(String xpath, String value, String prefixMappings) throws Docx4JException {

    try {
        getNamespaceContext().registerPrefixMappings(prefixMappings);

        Node n = (Node) xPath.evaluate(xpath, doc, XPathConstants.NODE);
        if (n == null) {
            log.debug("xpath returned null");
            return false;
        }
        log.debug(n.getClass().getName());

        // Method 1: Crimson throws error
        // Could avoid with System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
        //       "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        //n.setTextContent(value);

        // Method 2: crimson ignores
        // n.setNodeValue(value);

        // Method 3: createTextNode, then append it
        // First, need to delete/replace existing text node 
        if (n.getChildNodes() != null && n.getChildNodes().getLength() > 0) {
            NodeList nodes = n.getChildNodes();
            for (int i = nodes.getLength(); i > 0; i--) {
                n.removeChild(nodes.item(i - 1));
            }
        }
        Text t = n.getOwnerDocument().createTextNode(value);
        n.appendChild(t);

        // cache is now invalid
        return true;
    } catch (Exception e) {
        throw new Docx4JException("Problem setting value at xpath " + xpath);
    }

}

From source file:org.eclipse.ecr.common.xmap.DOMHelper.java

/**
 * Parses a string containing XML and returns a DocumentFragment containing
 * the nodes of the parsed XML.//w  ww.  j av  a2 s . c  o m
 */
public static void loadFragment(Element el, String fragment) {
    // Wrap the fragment in an arbitrary element
    fragment = "<fragment>" + fragment + "</fragment>";
    try {
        // Create a DOM builder and parse the fragment
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment)));

        Document doc = el.getOwnerDocument();

        // Import the nodes of the new document into doc so that they
        // will be compatible with doc
        Node node = doc.importNode(d.getDocumentElement(), true);

        // Create the document fragment node to hold the new nodes
        DocumentFragment docfrag = doc.createDocumentFragment();

        // Move the nodes into the fragment
        while (node.hasChildNodes()) {
            el.appendChild(node.removeChild(node.getFirstChild()));
        }

    } catch (Exception e) {
        log.error(e, e);
    }
}

From source file:org.eclipse.skalli.core.extension.DataMigration11.java

/**
 * Changes from model version 11 -> 12:
 * <ol>//from   ww  w  .  jav  a 2  s.c  o m
 *   <li>Project members now in separate collections</li>
 * </ol>
 */
@Override
public void migrate(Document doc) {
    Map<String, String> roleCache = new HashMap<String, String>();

    List<String> members = new LinkedList<String>();
    List<String> leads = new LinkedList<String>();
    List<String> productOwners = new LinkedList<String>();
    List<String> scrumMasters = new LinkedList<String>();

    // reading old project members and their roles
    NodeList nodes = doc.getElementsByTagName("org.eclipse.skalli.model.core.ProjectMember");
    for (int i = 0; i < nodes.getLength(); i++) {
        Element member = (Element) nodes.item(i);
        String userId = member.getElementsByTagName("userID").item(0).getTextContent();
        LOG.debug("Reading User '" + userId + "' for Migration.");

        NodeList roles = member.getElementsByTagName("roles").item(0).getChildNodes();
        for (int j = 0; j < roles.getLength(); j++) {
            Node roleNode = (Node) roles.item(j);
            if (roleNode instanceof Element && !roleNode.getNodeName().equals("no-comparator")) {
                Element roleElement = (Element) roleNode;
                String role = null;
                if (StringUtils.isBlank(roleElement.getAttribute("reference"))) {
                    role = roleElement.getElementsByTagName("technicalName").item(0).getTextContent();
                    roleCache.put(roleElement.getNodeName(), role);
                } else {
                    role = roleCache.get(roleElement.getNodeName());
                }
                LOG.debug("User '" + userId + "' has role '" + role + "'.");
                if (role.equals("projectmember")) {
                    members.add(userId);
                } else if (role.equals("projectlead")) {
                    leads.add(userId);
                } else if (role.equals("scrummaster")) {
                    scrumMasters.add(userId);
                } else if (role.equals("productowner")) {
                    productOwners.add(userId);
                } else {
                    throw new RuntimeException("unknown role: " + role);
                }
            }
        }
    }

    // remove current "members" section
    Node membersNode = doc.getElementsByTagName("members").item(0);
    if (membersNode == null) {
        throw new RuntimeException(doc.toString());
    }
    Node projectNode = membersNode.getParentNode();
    projectNode.removeChild(membersNode);

    // add (new) members
    addPeopleSection(doc, projectNode, "members", members);

    // add leads
    addPeopleSection(doc, projectNode, "leads", leads);

    // add scrum people
    if (scrumMasters.size() > 0 || productOwners.size() > 0) {
        Node scrumExt = doc.getElementsByTagName("org.eclipse.skalli.model.ext.scrum.ScrumProjectExt").item(0);

        if (scrumExt == null) {
            LOG.warn("there were scrum people, but no scrum extension.");
        } else {
            // add scrum masters
            addPeopleSection(doc, scrumExt, "scrumMasters", scrumMasters);

            // add product owners
            addPeopleSection(doc, scrumExt, "productOwners", productOwners);
        }
    }
}

From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java

/**
 * Resolves all &lt;include&gt; in a given schema and writes the
 * result to the given output stream. Includes that can't be resolved
 * are removed from the schema.// w  w w.  j  av a 2  s.  c  o m
 * @param in  the input stream providing the schema to resolve.
 * @param out  the output stream to write the result to.
 * @throws IOException  if an i/o error occured.
 * @throws SAXException  if parsing of the schema failed.
 * @throws ParserConfigurationException  indicates a serious parser configuration error.
 * @throws TransformerException  if transforming the schema DOM to a character stream failed.
 * @throws TransformerConfigurationException  indicates a serious transformer configuration error.
 */
private void resolveIncludes(InputStream in, OutputStream out) throws IOException, SAXException,
        ParserConfigurationException, TransformerConfigurationException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document schemaDOM = dbf.newDocumentBuilder().parse(new InputSource(in));
    Element schemaRoot = schemaDOM.getDocumentElement();

    // iterate all <include> tags and resolve them if possible
    NodeList includes = schemaDOM.getElementsByTagName("xsd:include");
    while (includes.getLength() > 0) {
        for (int i = 0; i < includes.getLength(); ++i) {
            Node includeNode = includes.item(i);
            Node includeParent = includeNode.getParentNode();
            Node schemaLocation = includeNode.getAttributes().getNamedItem("schemaLocation");
            if (schemaLocation != null) {
                // extract the pure file name from the schemaLocation and
                // try to find an XSD resource in all model extensions matching
                // the given schemaLocation attribute -> if found, replace the include tag
                // with the DOM of the include (without the root tag, of course!)
                URL includeFile = RestUtils.findSchemaResource(schemaLocation.getTextContent());
                if (includeFile != null) {
                    Document includeDOM = dbf.newDocumentBuilder()
                            .parse(new InputSource(includeFile.openStream()));
                    NodeList includeNodes = includeDOM.getDocumentElement().getChildNodes();
                    for (int j = 0; j < includeNodes.getLength(); ++j) {
                        // import and insert the tag before <include>
                        schemaRoot.insertBefore(schemaDOM.importNode(includeNodes.item(j), true), includeNode);
                    }
                }

                // in any case: remove the <include> tag
                includeParent.removeChild(includeNode);
            }
        }
        // resolve includes of includes (if any)
        includes = schemaDOM.getElementsByTagName("xsd:include");
    }

    // serialize the schema DOM to the given output stream
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.INDENT, "yes");
    xform.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    xform.transform(new DOMSource(schemaDOM), new StreamResult(out));
}

From source file:org.eclipse.smila.processing.pipelets.xmlprocessing.util.XPathUtils.java

/**
 * Removes nodes by XPath./* www  .j a  v  a2 s. co  m*/
 * 
 * @param node
 *          the Node
 * @param xpath
 *          the XPath
 * @param namespaceNode
 *          the namespace
 */
public static void removeNodesByXPath(Node node, String xpath, Node namespaceNode) {

    final Log log = LogFactory.getLog(XPathUtils.class);

    try {

        final XObject xobj = XPathAPI.eval(node, xpath, namespaceNode);

        if (xobj instanceof NodeSequence) {
            final NodeList nlTemp = xobj.nodelist();

            for (int i = 0; i < nlTemp.getLength(); i++) {
                final Node parent = nlTemp.item(i).getParentNode();
                parent.removeChild(nlTemp.item(i));
            }
            /*
             * } else if (xobj instanceof XBoolean) { xobj.nodelist() return new Boolean(xobj.bool()); } else if (xobj
             * instanceof XNumber) { return new Double(xobj.num()); } else if (xobj instanceof XRTreeFrag) { return
             * xobj.str(); } else if (xobj instanceof XString) { return xobj.str();
             */
        } else {
            throw new Exception("unsupported xpath return type [" + xobj.getClass().getName() + "]");
        }
    } catch (final Exception e) {
        log.error("unkown error occured", e);
    }
}