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:org.jasig.portal.layout.dlm.PositionManager.java

/**
   This method applies the ordering specified in the passed in order list
   to the child nodes of the compViewParent. Nodes specified in the list
   but located elsewhere are pulled in.//w w w .  j av a  2  s . co m
 */
static void applyToNodes(List<NodeInfo> order, Element compViewParent) {
    // first set up a bogus node to assist with inserting
    Node insertPoint = compViewParent.getOwnerDocument().createElement("bogus");
    Node first = compViewParent.getFirstChild();

    if (first != null)
        compViewParent.insertBefore(insertPoint, first);
    else
        compViewParent.appendChild(insertPoint);

    // now pass through the order list inserting the nodes as you go
    for (int i = 0; i < order.size(); i++)
        compViewParent.insertBefore(((NodeInfo) order.get(i)).node, insertPoint);

    compViewParent.removeChild(insertPoint);
}

From source file:org.kuali.rice.edl.impl.components.RefreshFromLookupComponent.java

public void updateDOM(Document dom, Element configElement, EDLContext edlContext) {
    String command = edlContext.getUserAction().getAction();
    if (UserAction.ACTION_REFRESH_FROM_LOOKUP.equals(command)) {
        RequestParser requestParser = edlContext.getRequestParser();

        Element currentVersion = VersioningPreprocessor.findCurrentVersion(dom);
        // First, create a list of all of the <field> tags that match the parameter names returned from the lookup
        List<Element> fieldsToDelete = new ArrayList<Element>();
        NodeList fieldNodes = currentVersion.getElementsByTagName("field");

        // get the list of input parameters returned from the lookup so we can clear empty ones as well
        List<String> requestParameterNames = requestParser.getParameterNames();

        for (int i = 0; i < fieldNodes.getLength(); i++) {
            Element fieldNode = (Element) fieldNodes.item(i);
            String fieldName = fieldNode.getAttribute("name");
            if (requestParameterNames.contains(fieldName)) {
                fieldsToDelete.add(fieldNode);
            }//from  w ww  .  j  a v a2s  . c om
        }

        // Second, delete those nodes; we will rely on normal population to recreate those nodes
        // if the nodes weren't deleted, EDL would continue to display the old value on the generated output
        for (Element fieldToDelete : fieldsToDelete) {
            currentVersion.removeChild(fieldToDelete);
        }
    }
}

From source file:org.kuali.rice.edl.impl.components.SelectControlEDLComponent.java

protected void includeValuesGroup(Element valuesGroupElem) {
    Element valuesGroupParent = (Element) valuesGroupElem.getParentNode();
    NodeList valuesGroupChildren = valuesGroupElem.getChildNodes();

    for (int index = 0; index < valuesGroupChildren.getLength(); index++) {
        Node item = valuesGroupChildren.item(index);
        if (Node.ELEMENT_NODE == item.getNodeType() && item.getNodeName().equals("values")) {
            valuesGroupParent.insertBefore(item, valuesGroupElem);
        }/*from   ww w.j  a  v a  2 s  .co m*/
    }
    valuesGroupParent.removeChild(valuesGroupElem);
}

From source file:org.kuali.rice.kew.mail.service.impl.StyleableEmailContentServiceImpl.java

/**
 * This method handles converting the DocumentRouteHeaderValue into an XML representation.  The reason we can't just use
 * propertiesToXml like we have elsewhere is because the doc header has a String attached to it that has the XML document
 * content in it.  The default serialization of this will serialize this as a String so we will end up with escaped XML
 * in our output which we won't be able to process with the email stylesheet.  So we need to read the xml content from
 * the document and parse it into a DOM object so it can be appended to our output.
 *//*from   w  w  w . j a  va2 s.co m*/
protected void addDocumentHeaderXML(Document document, DocumentRouteHeaderValue documentHeader, Node node,
        String elementName) throws Exception {
    Element element = XmlHelper.propertiesToXml(document, documentHeader, elementName);
    // now we need to "fix" the xml document content because it's going to be in there as escaped XML
    Element docContentElement = (Element) element.getElementsByTagName("docContent").item(0);
    String documentContent = docContentElement.getTextContent();

    if (!StringUtils.isBlank(documentContent) && documentContent.startsWith("<")) {
        Document documentContentXML = XmlHelper.readXml(documentContent);
        Element documentContentElement = documentContentXML.getDocumentElement();
        documentContentElement = (Element) document.importNode(documentContentElement, true);

        // remove the old, bad text content
        docContentElement.removeChild(docContentElement.getFirstChild());

        // replace with actual XML
        docContentElement.appendChild(documentContentElement);
    } else {
        // in this case it means that the XML is encrypted, unfortunately, we have no way to decrypt it since
        // the key is stored in the client application.  We will just include the doc content since none of our
        // current IU clients will be using this feature right away

        // remove the old, bad text content
        docContentElement.removeChild(docContentElement.getFirstChild());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(XmlJotter.jotNode(element));
    }

    node.appendChild(element);
}

From source file:org.kuali.rice.kns.workflow.attribute.KualiXmlAttributeHelper.java

/**
 * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
 * where the super class expects to see them, overwriting the original title in the XML.
 *
 * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
 *///from   ww  w. j  av a 2s  . co m

public Element processConfigXML(Element root, String[] xpathExpressionElements) {

    NodeList fields = root.getElementsByTagName("fieldDef");
    Element theTag = null;
    String docContent = "";

    /**
     * This section will check to see if document content has been defined in the configXML for the document type, by running an
     * XPath. If this is an empty list the xpath expression in the fieldDef is used to define the xml document content that is
     * added to the configXML. The xmldocument content is of this form, when in the document configXML. <xmlDocumentContent>
     * <org.kuali.rice.krad.bo.SourceAccountingLine> <amount> <value>%totaldollarAmount%</value> </amount>
     * </org.kuali.rice.krad.bo.SourceAccountingLine> </xmlDocumentContent> This class generates this on the fly, by creating an XML
     * element for each term in the XPath expression. When this doesn't apply XML can be coded in the configXML for the
     * ruleAttribute.
     *
     * @see org.kuali.rice.kew.plugin.attributes.WorkflowAttribute#getDocContent()
     */

    org.w3c.dom.Document xmlDoc = null;
    if (!xmlDocumentContentExists(root)) { // XML Document content is given because the xpath is non standard
        fields = root.getElementsByTagName("fieldDef");
        xmlDoc = root.getOwnerDocument();
    }
    for (int i = 0; i < fields.getLength(); i++) { // loop over each fieldDef
        String name = null;
        if (!xmlDocumentContentExists(root)) {
            theTag = (Element) fields.item(i);

            /*
             * Even though there may be multiple xpath test, for example one for source lines and one for target lines, the
             * xmlDocumentContent only needs one, since it is used for formatting. The first one is arbitrarily selected, since
             * they are virtually equivalent in structure, most of the time.
             */

            List<String> xPathTerms = getXPathTerms(theTag);
            if (xPathTerms.size() != 0) {
                Node iterNode = xmlDoc.createElement("xmlDocumentContent");

                xmlDoc.normalize();

                iterNode.normalize();

                /*
                 * Since this method is run once per attribute and there may be multiple fieldDefs, the first fieldDef is used
                 * to create the configXML.
                 */
                for (int j = 0; j < xPathTerms.size(); j++) {// build the configXML based on the Xpath
                    // TODO - Fix the document content element generation
                    iterNode.appendChild(xmlDoc.createElement(xPathTerms.get(j)));
                    xmlDoc.normalize();

                    iterNode = iterNode.getFirstChild();
                    iterNode.normalize();

                }
                iterNode.setTextContent("%" + xPathTerms.get(xPathTerms.size() - 1) + "%");
                root.appendChild(iterNode);
            }
        }
        theTag = (Element) fields.item(i);
        // check to see if a values finder is being used to set valid values for a field
        NodeList displayTagElements = theTag.getElementsByTagName("display");
        if (displayTagElements.getLength() == 1) {
            Element displayTag = (Element) displayTagElements.item(0);
            List valuesElementsToAdd = new ArrayList();
            for (int w = 0; w < displayTag.getChildNodes().getLength(); w++) {
                Node displayTagChildNode = (Node) displayTag.getChildNodes().item(w);
                if ((displayTagChildNode != null) && ("values".equals(displayTagChildNode.getNodeName()))) {
                    if (displayTagChildNode.getChildNodes().getLength() > 0) {
                        String valuesNodeText = displayTagChildNode.getFirstChild().getNodeValue();
                        String potentialClassName = getPotentialKualiClassName(valuesNodeText,
                                KUALI_VALUES_FINDER_REFERENCE_PREFIX, KUALI_VALUES_FINDER_REFERENCE_SUFFIX);
                        if (StringUtils.isNotBlank(potentialClassName)) {
                            try {
                                Class finderClass = Class.forName((String) potentialClassName);
                                KeyValuesFinder finder = (KeyValuesFinder) finderClass.newInstance();
                                NamedNodeMap valuesNodeAttributes = displayTagChildNode.getAttributes();
                                Node potentialSelectedAttribute = (valuesNodeAttributes != null)
                                        ? valuesNodeAttributes.getNamedItem("selected")
                                        : null;
                                for (Iterator iter = finder.getKeyValues().iterator(); iter.hasNext();) {
                                    KeyValue keyValue = (KeyValue) iter.next();
                                    Element newValuesElement = root.getOwnerDocument().createElement("values");
                                    newValuesElement.appendChild(
                                            root.getOwnerDocument().createTextNode(keyValue.getKey()));
                                    // newValuesElement.setNodeValue(KeyValue.getKey().toString());
                                    newValuesElement.setAttribute("title", keyValue.getValue());
                                    if (potentialSelectedAttribute != null) {
                                        newValuesElement.setAttribute("selected",
                                                potentialSelectedAttribute.getNodeValue());
                                    }
                                    valuesElementsToAdd.add(newValuesElement);
                                }
                            } catch (ClassNotFoundException cnfe) {
                                String errorMessage = "Caught an exception trying to find class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, cnfe);
                                throw new RuntimeException(errorMessage, cnfe);
                            } catch (InstantiationException ie) {
                                String errorMessage = "Caught an exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, ie);
                                throw new RuntimeException(errorMessage, ie);
                            } catch (IllegalAccessException iae) {
                                String errorMessage = "Caught an access exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, iae);
                                throw new RuntimeException(errorMessage, iae);
                            }
                        } else {
                            valuesElementsToAdd.add(displayTagChildNode.cloneNode(true));
                        }
                        displayTag.removeChild(displayTagChildNode);
                    }
                }
            }
            for (Iterator iter = valuesElementsToAdd.iterator(); iter.hasNext();) {
                Element valuesElementToAdd = (Element) iter.next();
                displayTag.appendChild(valuesElementToAdd);
            }
        }
        if ((xpathExpressionElements != null) && (xpathExpressionElements.length > 0)) {
            NodeList fieldEvaluationElements = theTag.getElementsByTagName("fieldEvaluation");
            if (fieldEvaluationElements.getLength() == 1) {
                Element fieldEvaluationTag = (Element) fieldEvaluationElements.item(0);
                List tagsToAdd = new ArrayList();
                for (int w = 0; w < fieldEvaluationTag.getChildNodes().getLength(); w++) {
                    Node fieldEvaluationChildNode = (Node) fieldEvaluationTag.getChildNodes().item(w);
                    Element newTagToAdd = null;
                    if ((fieldEvaluationChildNode != null)
                            && ("xpathexpression".equals(fieldEvaluationChildNode.getNodeName()))) {
                        newTagToAdd = root.getOwnerDocument().createElement("xpathexpression");
                        newTagToAdd.appendChild(root.getOwnerDocument()
                                .createTextNode(generateNewXpathExpression(
                                        fieldEvaluationChildNode.getFirstChild().getNodeValue(),
                                        xpathExpressionElements)));
                        tagsToAdd.add(newTagToAdd);
                        fieldEvaluationTag.removeChild(fieldEvaluationChildNode);
                    }
                }
                for (Iterator iter = tagsToAdd.iterator(); iter.hasNext();) {
                    Element elementToAdd = (Element) iter.next();
                    fieldEvaluationTag.appendChild(elementToAdd);
                }
            }
        }
        theTag.setAttribute("title", getBusinessObjectTitle(theTag));

    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(XmlJotter.jotNode(root));
        StringWriter xmlBuffer = new StringWriter();
        try {

            root.normalize();
            Source source = new DOMSource(root);
            Result result = new StreamResult(xmlBuffer);
            TransformerFactory.newInstance().newTransformer().transform(source, result);
        } catch (Exception e) {
            LOG.debug(" Exception when printing debug XML output " + e);
        }
        LOG.debug(xmlBuffer.getBuffer());
    }

    return root;
}

From source file:org.mule.module.xml.config.XsltTextDefinitionParser.java

protected void postProcess(ParserContext context, BeanAssembler assembler, Element element) {
    NodeList children = element.getChildNodes();
    if (0 != children.getLength()) {
        Element stylesheet = null;
        for (int i = 0; i < children.getLength(); i++) {
            if (Node.ELEMENT_NODE == children.item(i).getNodeType()) {
                assertArgument(null == stylesheet, "XSLT transformer can have at most one child element");
                stylesheet = (Element) children.item(i);
            }/*from  www  .  jav a2s  .  c o m*/
        }
        if (null != stylesheet) {
            assertArgument(STYLESHEET.equals(stylesheet.getLocalName()),
                    "XSLT transformer child element must be named " + STYLESHEET);
            assembler.extendTarget("xslt", domToString(stylesheet), false);
            // block processing by Spring
            element.removeChild(stylesheet);
        }
    }
    super.postProcess(context, assembler, element);
}

From source file:org.ncbo.stanford.service.xml.impl.XMLSerializationServiceImpl.java

private void removeWhitespaceNodes(Element e) {
    NodeList children = e.getChildNodes();

    for (int i = children.getLength() - 1; i >= 0; i--) {
        Node child = children.item(i);

        if (child instanceof Text && ((Text) child).getData().trim().length() == 0) {
            e.removeChild(child);
        } else if (child instanceof Element) {
            removeWhitespaceNodes((Element) child);
        }//from  ww  w.ja va2 s .  com
    }
}

From source file:org.nuxeo.runtime.model.persistence.fs.FileSystemStorage.java

@Override
public Contribution updateContribution(Contribution contribution) {
    File file = new File(root, contribution.getName() + ".xml");
    String content = safeRead(file);
    DocumentBuilder docBuilder;/*  ww w .  j a v  a  2 s .  c om*/
    try {
        docBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Document doc;
    try {
        doc = docBuilder.parse(new ByteArrayInputStream(content.getBytes()));
    } catch (SAXException | IOException e) {
        throw new RuntimeException(e);
    }
    Element root = doc.getDocumentElement();
    if (contribution.isDisabled()) {
        root.setAttribute("disabled", "true");
    } else {
        root.removeAttribute("disabled");
    }
    Node node = root.getFirstChild();
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE && "documentation".equals(node.getNodeName())) {
            break;
        }
        node = node.getNextSibling();
    }
    String description = contribution.getDescription();
    if (description == null) {
        description = "";
    }
    if (node != null) {
        root.removeChild(node);
    }
    Element el = doc.createElement("documentation");
    el.appendChild(doc.createTextNode(description));
    root.appendChild(el);

    try {
        safeWrite(file, DOMSerializer.toString(doc));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return getContribution(contribution.getName());
}

From source file:org.ojbc.bundles.adapters.personsearch.ndex.CamelContextTest.java

private Document buildPersonSearchMessage() throws Exception {
    Document personSearchRequestMessage = buildPersonSearchRequestMessagePersonNameOnly("System ID");
    Element personElement = (Element) XmlUtils.xPathNodeSearch(personSearchRequestMessage,
            "psr-doc:PersonSearchRequest/psr:Person");
    Element personNameElement = (Element) XmlUtils.xPathNodeSearch(personElement, "nc:PersonName");
    Element lastNameElement = (Element) XmlUtils.xPathNodeSearch(personNameElement, "nc:PersonSurName");
    lastNameElement.setTextContent("Ivey");
    Element firstNameElement = (Element) XmlUtils.xPathNodeSearch(personNameElement, "nc:PersonGivenName");
    personNameElement.removeChild(firstNameElement);
    Element middleNameElement = (Element) XmlUtils.xPathNodeSearch(personNameElement, "nc:PersonMiddleName");
    personNameElement.removeChild(middleNameElement);
    return personSearchRequestMessage;
}

From source file:org.ojbc.bundles.adapters.personsearch.ndex.CamelContextTest.java

private Document buildPersonSearchRequestMessagePersonNameOnly(String systemId) throws Exception {
    File inputFile = new File("src/test/resources/xml/BasePersonSearchRequest.xml");
    Document ret = documentBuilder.parse(new FileInputStream(inputFile));
    Element systemElement = (Element) XmlUtils.xPathNodeSearch(ret.getDocumentElement(),
            "psr:SourceSystemNameText");
    systemElement.setTextContent(systemId);
    Document personSearchRequestMessage = ret;
    Element personElement = (Element) XmlUtils.xPathNodeSearch(personSearchRequestMessage,
            "psr-doc:PersonSearchRequest/psr:Person");
    NodeList children = personElement.getChildNodes();
    int childCount = children.getLength();
    for (int i = childCount - 1; i >= 0; i--) {
        Node child = children.item(i);
        if (!("PersonName".equals(child.getLocalName()))) {
            personElement.removeChild(child);
        }//from   ww  w .  ja  v  a  2  s .  c  o  m
    }

    //XmlUtils.printNode(personSearchRequestMessage);
    return personSearchRequestMessage;
}