Example usage for org.w3c.dom Element getParentNode

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

Introduction

In this page you can find the example usage for org.w3c.dom Element getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:com.geodan.ngr.serviceintegration.CSWTransformer.java

/**
 * Gets the title of the dataset from the element "el". Because the
 * title is in a different part of the XML we use getParentNode.
 * We were not successful using XPath./*w w w  . j a va 2 s.com*/
 * With getParentNode we navigate to the element "MD_Metadata" from
 * there we go to "gmd:MD_DataIdentification" where we look for the title
 *
 * @param el   the element that contains the title
 * @return      title of the element
 * @throws Exception in case of exception
 */
protected String findTitle(Element el) throws Exception {
    String title = null;
    // CI.online
    // ......trasferoptions...transferoptions.distribution....distriinfo...metadata
    Element elem_MD_Metadata = (Element) el.getParentNode().getParentNode().getParentNode().getParentNode()
            .getParentNode().getParentNode();
    NodeList nl_di = elem_MD_Metadata.getElementsByTagName("gmd:MD_DataIdentification");

    if (nl_di.getLength() > 0) {
        title = getValue((Element) nl_di.item(0), "gmd:title");
    }
    return title;
}

From source file:com.geodan.ngr.serviceintegration.CSWTransformer.java

/**
 * Gets the description (abstract) of the dataset from the element "el". Because the
 * abstract is in a different part of the XML we use getParentNode.
 * We were not successful using XPath./* w  ww .  j  av  a 2  s . c o  m*/
 * With getParentNode we navigate to the element "MD_Metadata" from
 * there we go to "gmd:MD_DataIdentification" where we look for the abstract
 *
 * @param el  the element that contains the title
 * @return    title of the element
 * @throws Exception in case of exception
 */
protected String findDescription(Element el) throws Exception {
    String description = null;
    // CI.online
    // ......trasferoptions...transferoptions.distribution....distriinfo...metadata
    Element elem_MD_Metadata = (Element) el.getParentNode().getParentNode().getParentNode().getParentNode()
            .getParentNode().getParentNode();
    NodeList nl_di = elem_MD_Metadata.getElementsByTagName("gmd:MD_DataIdentification");

    if (nl_di.getLength() > 0) {
        description = getValue((Element) nl_di.item(0), "gmd:abstract");
    }
    return description;
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.WsdlMimeMessageResponse.java

private void expandMtomAttachments(WsdlRequest wsdlRequest) {
    try {//from   w  w w  .  j  ava 2s . c  om
        // XmlObject xmlObject = XmlObject.Factory.parse( getContentAsString()
        // );
        XmlObject xmlObject = XmlUtils.createXmlObject(getContentAsString());
        XmlObject[] includes = xmlObject
                .selectPath("declare namespace xop='http://www.w3.org/2004/08/xop/include'; //xop:Include");

        for (XmlObject include : includes) {
            Element elm = (Element) include.getDomNode();
            String href = elm.getAttribute("href");
            Attachment attachment = getMmSupport().getAttachmentWithContentId("<" + href.substring(4) + ">");
            if (attachment != null) {
                ByteArrayOutputStream data = Tools.readAll(attachment.getInputStream(), 0);
                byte[] byteArray = data.toByteArray();

                XmlCursor cursor = include.newCursor();
                cursor.toParent();
                XmlObject parentXmlObject = cursor.getObject();
                cursor.dispose();

                SchemaType schemaType = parentXmlObject.schemaType();
                Node parentNode = elm.getParentNode();

                if (schemaType.isNoType()) {
                    SchemaTypeSystem typeSystem = wsdlRequest.getOperation().getInterface().getWsdlContext()
                            .getSchemaTypeSystem();
                    SchemaGlobalElement schemaElement = typeSystem
                            .findElement(new QName(parentNode.getNamespaceURI(), parentNode.getLocalName()));
                    if (schemaElement != null) {
                        schemaType = schemaElement.getType();
                    }
                }

                String txt = null;

                if (SchemaUtils.isInstanceOf(schemaType, XmlHexBinary.type)) {
                    txt = new String(Hex.encodeHex(byteArray));
                } else {
                    txt = new String(Base64.encodeBase64(byteArray));
                }

                parentNode.replaceChild(elm.getOwnerDocument().createTextNode(txt), elm);
            }
        }

        getMmSupport().setResponseContent(xmlObject.toString());
    } catch (Exception e) {
        SoapUI.logError(e);
    }
}

From source file:net.sf.jclal.experiment.ExperimentBuilder.java

private int expandElementsIterateAtributes(Element element, int[] configurationSchema) {
    NamedNodeMap attributes = element.getAttributes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);

        if (attribute.getNodeName().equals("multi")) {
            NodeList list = element.getElementsByTagName(element.getNodeName());

            for (int j = 0; j < configurationSchema.length; j++) {
                if (configurationSchema[j] != -1) {
                    element.getParentNode().replaceChild(list.item(configurationSchema[j]), element);

                    configurationSchema[j] = -1;
                    break;
                }// w  ww .  j  a  va 2s .co m
            }

            list = element.getChildNodes();

            for (int j = 0; j < list.getLength(); j++) {
                if (list.item(j).getNodeName().equals(attribute.getNodeName())) {
                    element.removeChild(list.item(j));
                }
            }

            return 1;
        }
    }

    return 0;
}

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 w  w w.j  a v  a 2s .c  o  m*/

    //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);
}

From source file:eu.europa.ec.markt.dss.applet.view.validationpolicy.EditView.java

private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath,
        final XmlDomAdapterNode clickedItem, final JTree tree) {
    final Element clickedElement = (Element) clickedItem.node;
    // popup menu for list -> add
    final JPopupMenu popup = new JPopupMenu();
    //delete node
    final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE"));
    menuItemToDelete.addActionListener(new ActionListener() {
        @Override//from w ww  . j a v a 2s  . c  om
        public void actionPerformed(ActionEvent actionEvent) {
            // find the order# of the child to delete
            final int index = clickedItem.getParent().index(clickedItem);

            Node oldChild = clickedElement.getParentNode().removeChild(clickedElement);
            if (index > -1) {
                validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild);
            }
        }
    });
    popup.add(menuItemToDelete);

    //Add node/value
    final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree();
    final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree);
    for (final XsdNode xsdChild : children) {
        final String xmlName = xsdChild.getLastNameOfPath();

        final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " "
                + xsdChild.getType().toString().toLowerCase() + ")");
        popup.add(menuItem);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Document document = getModel().getValidationPolicy().getDocument();

                final Node newElement;
                if (xsdChild.getType() == XsdNodeType.TEXT) {
                    // TEXT element always appended (last child)
                    newElement = clickedElement.appendChild(document.createTextNode("VALUE"));
                } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) {
                    newElement = document.createAttributeNS(null, xmlName);
                    ((Attr) newElement).setValue("VALUE");
                    clickedElement.setAttributeNode((Attr) newElement);
                } else if (xsdChild.getType() == XsdNodeType.ELEMENT) {
                    final Element childToAdd = document
                            .createElementNS("http://dss.markt.ec.europa.eu/validation/diagnostic", xmlName);
                    // find the correct possition to add the child
                    // Get all allowed children
                    Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree);
                    boolean toAddSeen = false;
                    Element elementIsToAddBeforeThisOne = null;
                    for (final XsdNode allowed : childrenMap.keySet()) {
                        if (!toAddSeen && allowed == xsdChild) {
                            toAddSeen = true;
                            continue;
                        }
                        if (toAddSeen) {
                            final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS(
                                    "http://dss.markt.ec.europa.eu/validation/diagnostic",
                                    allowed.getLastNameOfPath());
                            if (elementsByTagNameNS.getLength() > 0) {
                                // we found an element that is supposed to be after the one to add
                                elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0);
                                break;
                            }
                        }
                    }

                    if (elementIsToAddBeforeThisOne != null) {
                        newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne);
                    } else {
                        newElement = clickedElement.appendChild(childToAdd);
                    }
                } else {
                    throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType());
                }

                document.normalizeDocument();

                int indexOfAddedItem = 0;
                final int childCount = clickedItem.childCount();
                for (int i = 0; i < childCount; i++) {
                    if (clickedItem.child(i).node == newElement) {
                        indexOfAddedItem = i;
                        break;
                    }
                }

                TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath,
                        new int[] { indexOfAddedItem }, new Object[] { newElement });
                validationPolicyTreeModel.fireTreeNodesInserted(event);
                tree.expandPath(selectedPath);

                //Update model
                getModel().getValidationPolicy().setXmlDom(new XmlDom(document));
            }
        });

    }
    popup.show(tree, mouseEvent.getX(), mouseEvent.getY());
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method processes the SOAP response from the IdP, and converts it
 * for presenting it back to the WSP that requested a delegated SAML
 * assertion.//from  ww  w .  j av  a2  s  .c  om
 * 
 * @param samlSession SAML session
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 5 of 5: Processing SOAP response");

    try {
        String expression = "/soap:Envelope/soap:Header/ecp:Response";
        InputStream is = new ByteArrayInputStream(authnState.getSoapResponse().getBytes());
        InputSource source = new InputSource(is);
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.parse(source);
        Document doc = parser.getDocument();
        Node node = EXPRESSION_POOL.evaluate(expression, doc, XPathConstants.NODE);

        if (node != null) {
            String responseConsumerURL = node.getAttributes().getNamedItem("AssertionConsumerServiceURL")
                    .getTextContent();

            logger.debug("Found {} node found in SOAP response.", expression);

            if (responseConsumerURL != null
                    && responseConsumerURL.equals(authnState.getResponseConsumerURL())) {
                logger.debug("responseConsumerURL {} matches {}", responseConsumerURL,
                        authnState.getResponseConsumerURL());

                // Retrieve and save the SOAP prefix used
                String soapPrefix = node.getParentNode().getPrefix();
                Element ecpResponse = (Element) node;
                Element soapHeader = (Element) ecpResponse.getParentNode();
                removeAllChildren(soapHeader);

                // Now on to the PAOS Response
                Element paosResponse = doc.createElementNS("urn:liberty:paos:2003-08", "paos:Response");
                paosResponse.setAttribute(soapPrefix + ":mustUnderstand", "1");
                paosResponse.setAttribute(soapPrefix + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

                // messageID is optional
                if (authnState.getPaosMessageID() != null)
                    paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());

                soapHeader.appendChild(paosResponse);

                if (authnState.getRelayStateElement() != null) {
                    Node relayState = doc.importNode(authnState.getRelayStateElement(), true);
                    soapHeader.appendChild(relayState);
                }

                // Store the modified SOAP Request in the SAML Session
                String modifiedSOAPResponse = writeDomToString(doc);
                authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
                return true;
            }

            logger.debug("responseConsumerURL {} does not match {}", responseConsumerURL,
                    authnState.getResponseConsumerURL());
            Document soapFaultMessage = createSOAPFaultDocument(
                    "AssertionConsumerServiceURL attribute missing or not matching the expected value.");
            Element soapHeader = (Element) soapFaultMessage.getFirstChild().getFirstChild();
            // Now on to the PAOS Response
            Element paosResponse = soapFaultMessage.createElementNS("urn:liberty:paos:2003-08",
                    "paos:Response");
            paosResponse.setAttribute(SOAP_PREFIX + ":mustUnderstand", "1");
            paosResponse.setAttribute(SOAP_PREFIX + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

            // messageID is optional
            if (authnState.getPaosMessageID() != null) {
                paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());
            }

            soapHeader.appendChild(paosResponse);

            if (authnState.getRelayStateElement() != null) {
                Node relayState = soapFaultMessage.importNode(authnState.getRelayStateElement(), true);
                soapHeader.appendChild(relayState);
            }
            // Store the SOAP Fault in the SAML Session
            String modifiedSOAPResponse = writeDomToString(soapFaultMessage);
            authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
            sendSOAPFault(samlSession, authnState);
            return false;

        }

        // There was no response for the ECP.  Look for and propagate an error.
        String errorMessage = getSOAPFaultAsString(is);

        logger.warn("No {} node found in SOAP response. Error: {}", expression, errorMessage);

        if (errorMessage != null) {
            throw new DelegatedAuthenticationRuntimeException(errorMessage);
        }

        return false;
    } catch (XPathExpressionException ex) {
        logger.error("XPath programming error.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotRecognizedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotSupportedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (SAXException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (DOMException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (IOException ex) {
        logger.error(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
        throw new DelegatedAuthenticationRuntimeException(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
    } catch (SOAPException ex) {
        logger.error("Error processing a SOAP message.", ex);
        throw new DelegatedAuthenticationRuntimeException("Error processing a SOAP message.", ex);
    }
}

From source file:de.betterform.agent.web.flux.FluxProcessor.java

/**
 * listen to processor with XMLEvents and add a xmlEvent object to the
 * EventQueue for every incoming DOM Event from the processor.
 *
 * @param event the handled DOMEvent//from w ww.j  av a2  s  .c  om
 */
public void handleEvent(Event event) {
    super.handleEvent(event);
    try {
        if (event instanceof XMLEvent) {
            XMLEvent xmlEvent = (XMLEvent) event;
            String type = xmlEvent.getType();

            if (BetterFormEventNames.REPLACE_ALL.equals(type)
                    || BetterFormEventNames.REPLACE_ALL_XFORMS.equals(type)) {
                // get event context and store it in session
                Map submissionResponse = new HashMap();
                submissionResponse.put("header", xmlEvent.getContextInfo("header"));
                submissionResponse.put("body", xmlEvent.getContextInfo("body"));
                this.xformsProcessor.setContextParam(WebFactory.BETTERFORM_SUBMISSION_RESPONSE,
                        submissionResponse);

                // add event properties to log
                xmlEvent.addProperty("webcontext", (String) getContextParam("contextroot"));
                this.eventQueue.add(xmlEvent);

                this.exitEvent = xmlEvent;
                shutdown();
                return;
            } else if (BetterFormEventNames.LOAD_URI.equals(type)) {
                // get event properties
                String show = (String) xmlEvent.getContextInfo("show");
                if ("embed".equals(show)) {
                    Element targetElement = (Element) xmlEvent.getContextInfo("targetElement");
                    StringWriter result = new StringWriter();
                    generateUI(targetElement, result);
                    xmlEvent.addProperty("targetElement", result.toString());
                    /*
                                            if(LOGGER.isDebugEnabled()) {
                    DOMUtil.prettyPrintDOM(targetElement);
                    LOGGER.debug("xf:load show=\"embed\" Markup: \n" + result.toString() +"\n");
                                            }
                                            DOMUtil.prettyPrintDOM(targetElement);
                                            System.out.println("xf:load show=\"embed\" Markup: \n" + result.toString() +"\n");
                    */
                }

                // add event to log
                this.eventQueue.add(xmlEvent);
                if ("replace".equals(show)) {
                    this.exitEvent = xmlEvent;
                    shutdown();
                    //this.xformsSession.getManager().deleteXFormsSession(this.xformsSession.getKey());
                    WebUtil.removeSession(getKey());
                }

                return;
            } else if (BetterFormEventNames.STATE_CHANGED.equals(type)) {
                /*
                todo: This is a HACK cause BETTERFORM_STATE_CHANGED events are not sent consistently. For some reason
                todo: datatype changes are not always signalled e.g. when the datatype changes from a 'date' to
                todo: a 'string'. This should be fixed in betterForm Core - after that this branch should be removed again.
                 */

                // get event properties
                Element target = (Element) event.getTarget();
                String targetId = target.getAttributeNS(null, "id");
                String targetName = target.getLocalName();
                String dataType = (String) xmlEvent.getContextInfo("type");
                if (dataType == null) {
                    XFormsElement control = lookup(targetId);

                    //todo: this is copied from EventLog code - this is really a HACK!
                    if (EventQueue.HELPER_ELEMENTS.contains(targetName)) {
                        String parentId = ((Element) target.getParentNode()).getAttributeNS(null, "id");
                        xmlEvent.addProperty("parentId", parentId);
                    } else if (control instanceof BindingElement) {
                        if (LOGGER.isDebugEnabled()) {
                            DOMUtil.prettyPrintDOM(control.getElement());
                        }

                        Element bfData = DOMUtil.getChildElement(control.getElement(),
                                NamespaceConstants.BETTERFORM_PREFIX + ":data");
                        if (bfData != null) {
                            String internalType = bfData.getAttributeNS(NamespaceConstants.BETTERFORM_NS,
                                    "type");
                            xmlEvent.addProperty("type", internalType);
                        }
                    }
                }
                this.eventQueue.add(xmlEvent);
                return;
            } else if (XFormsEventNames.VERSION_EXCEPTION.equals(type)) {
                WebUtil.removeSession(getKey());
                xmlEvent.addProperty("errorinformation", xmlEvent.getContextInfo().get("error-information"));
            }
            this.eventQueue.add(xmlEvent);
        }
    } catch (Exception e) {
        handleEventException(e);
    }
}

From source file:eu.europa.esig.dss.applet.view.validationpolicy.EditView.java

private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath,
        final XmlDomAdapterNode clickedItem, final JTree tree) {
    final Element clickedElement = (Element) clickedItem.node;
    // popup menu for list -> add
    final JPopupMenu popup = new JPopupMenu();
    //delete node
    final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE"));
    menuItemToDelete.addActionListener(new ActionListener() {
        @Override/* w w  w  .j  a va2  s.c o m*/
        public void actionPerformed(ActionEvent actionEvent) {
            // find the order# of the child to delete
            final int index = clickedItem.getParent().index(clickedItem);

            Node oldChild = clickedElement.getParentNode().removeChild(clickedElement);
            if (index > -1) {
                validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild);
            }
        }
    });
    popup.add(menuItemToDelete);

    //Add node/value
    final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree();
    final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree);
    for (final XsdNode xsdChild : children) {
        final String xmlName = xsdChild.getLastNameOfPath();

        final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " "
                + xsdChild.getType().toString().toLowerCase() + ")");
        popup.add(menuItem);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Document document = getModel().getValidationPolicy().getDocument();

                final Node newElement;
                if (xsdChild.getType() == XsdNodeType.TEXT) {
                    // TEXT element always appended (last child)
                    newElement = clickedElement.appendChild(document.createTextNode("VALUE"));
                } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) {
                    newElement = document.createAttributeNS(null, xmlName);
                    ((Attr) newElement).setValue("VALUE");
                    clickedElement.setAttributeNode((Attr) newElement);
                } else if (xsdChild.getType() == XsdNodeType.ELEMENT) {
                    final Element childToAdd = document
                            .createElementNS("http://dss.esig.europa.eu/validation/diagnostic", xmlName);
                    // find the correct possition to add the child
                    // Get all allowed children
                    Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree);
                    boolean toAddSeen = false;
                    Element elementIsToAddBeforeThisOne = null;
                    for (final XsdNode allowed : childrenMap.keySet()) {
                        if (!toAddSeen && (allowed == xsdChild)) {
                            toAddSeen = true;
                            continue;
                        }
                        if (toAddSeen) {
                            final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS(
                                    "http://dss.esig.europa.eu/validation/diagnostic",
                                    allowed.getLastNameOfPath());
                            if (elementsByTagNameNS.getLength() > 0) {
                                // we found an element that is supposed to be after the one to add
                                elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0);
                                break;
                            }
                        }
                    }

                    if (elementIsToAddBeforeThisOne != null) {
                        newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne);
                    } else {
                        newElement = clickedElement.appendChild(childToAdd);
                    }
                } else {
                    throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType());
                }

                document.normalizeDocument();

                int indexOfAddedItem = 0;
                final int childCount = clickedItem.childCount();
                for (int i = 0; i < childCount; i++) {
                    if (clickedItem.child(i).node == newElement) {
                        indexOfAddedItem = i;
                        break;
                    }
                }

                TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath,
                        new int[] { indexOfAddedItem }, new Object[] { newElement });
                validationPolicyTreeModel.fireTreeNodesInserted(event);
                tree.expandPath(selectedPath);

                //Update model
                getModel().getValidationPolicy().setXmlDom(new XmlDom(document));
            }
        });

    }
    popup.show(tree, mouseEvent.getX(), mouseEvent.getY());
}

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

public static Element renameElement(Element elem, String newName) {
    Document doc = elem.getOwnerDocument();

    // Create an element with the new name
    Element elem2 = doc.createElement(newName);

    // Copy the attributes to the new element
    NamedNodeMap attrs = elem.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
        elem2.getAttributes().setNamedItem(attr2);
    }/*from w w w  .ja v a2  s .  c  o m*/

    // Move all the children
    while (elem.hasChildNodes()) {
        elem2.appendChild(elem.getFirstChild());
    }

    // Replace the old node with the new node
    elem.getParentNode().replaceChild(elem2, elem);

    return elem2;
}