Example usage for org.dom4j Element remove

List of usage examples for org.dom4j Element remove

Introduction

In this page you can find the example usage for org.dom4j Element remove.

Prototype

boolean remove(Text text);

Source Link

Document

Removes the given Text if the node is an immediate child of this element.

Usage

From source file:com.amalto.workbench.utils.MDMServerHelper.java

License:Open Source License

public static boolean deleteServer(String name) {
    boolean deleted = false;
    Element rootElement = getRootElement();
    Element serverElement = getServerElement(rootElement, name);
    if (serverElement != null) {
        rootElement.remove(serverElement);
        deleted = saveRootElement(rootElement);
    }//w w w. jav a  2 s  . c o  m
    return deleted;
}

From source file:com.amalto.workbench.utils.MDMServerHelper.java

License:Open Source License

public static boolean updateServer(MDMServerDef oldServerDef, MDMServerDef newServerDef) {
    Element rootElement = getRootElement();
    String oldName = oldServerDef.getName();
    Element serverElement = null;
    String newName = newServerDef.getName();
    if (oldName.equals(newName)) {
        serverElement = getServerElement(rootElement, oldName);
    } else {//  w ww .  ja va  2s  .  co m
        serverElement = getServerElement(rootElement, oldName);
        if (serverElement != null) {
            rootElement.remove(serverElement);
        }
        serverElement = getServerElement(rootElement, newName);
    }
    if (serverElement == null) {
        addServerElement(rootElement, newServerDef);
    } else {
        addServerProperties(serverElement, newServerDef);
    }

    return saveRootElement(rootElement);
}

From source file:com.beacon.wlsagent.xml.XmlWorker.java

public Document genMonXml(Document document, BeaconStateCollector fsc) {
    Document resultDoc = null;//w w w .  j  av a 2 s  . c o  m

    if (fsc.isConnectedToAdmin()) {

        resultDoc = DocumentHelper.createDocument();

        Element root = resultDoc.addElement("MONITOR").addAttribute("Date", BeaconUtil.getStringDate());
        Element osEle = root.addElement("OSResource");

        String cpuStr = BeaconUtil.runShell("sh bin/getCPU.sh");
        String memStr = BeaconUtil.runShell("sh bin/getMEM.sh");
        if ((cpuStr == "") || (memStr == "")) {
            cpuStr = (String) BeaconUtil.runShell().get("CPU");
            memStr = (String) BeaconUtil.runShell().get("MEM");
        }
        osEle.addAttribute("CPU", cpuStr).addAttribute("MEM", memStr);

        List mbeanEleList = document.selectNodes("//MBean");

        ObjectName[] svrRt = fsc.getServerRT();

        int svrRtCount = svrRt.length;

        int f = 0;
        for (Iterator i = mbeanEleList.iterator(); i.hasNext();) {
            Element mbeanEle = (Element) i.next();
            String mbeanName = mbeanEle.attributeValue("name");
            log.debug("Currently dealing with mbean: " + mbeanName);
            Iterator k = mbeanEle.elementIterator("attribute");

            List al = new ArrayList();
            for (; k.hasNext(); f++) {
                al.add(((Element) k.next()).getText());
            }
            String mbeanAttrStrs[] = BeaconUtil.listToStrArray(al);

            for (int m = 0; m < svrRtCount; m++) {
                Map mBeanInfoMap[] = fsc.getMBeanInfoMaps(mbeanAttrStrs, mbeanName, svrRt[m]);
                String svrName = svrRt[m].getKeyProperty("Name");
                log.debug("Currently dealing with server: " + svrRt[m]);
                if (mBeanInfoMap != null) {
                    for (int g = 0; g < mBeanInfoMap.length; g++) {
                        if (mBeanInfoMap[g] != null && mbeanAttrStrs.length > 0) {
                            Element currItem = root.addElement(mbeanName);
                            currItem.addAttribute("serverName", svrName);
                            for (int j = 0; j < mbeanAttrStrs.length; j++) {
                                String curAttr = mbeanAttrStrs[j];
                                Object curAttrVal = mBeanInfoMap[g].get(curAttr);
                                if (curAttrVal != null) {
                                    currItem.addAttribute(curAttr, String.valueOf(curAttrVal));
                                } else {
                                    root.remove(currItem);
                                    j = mbeanAttrStrs.length;
                                }
                                log.debug("Attribute: " + curAttr + " Value: "
                                        + String.valueOf(mBeanInfoMap[g].get(curAttr)));
                            }

                        }
                    }
                }
            }

        }
    } else {
        resultDoc = this.genErrXml("Happened to lose connection to WebLogic Admin. maybe shutdown");
    }

    return resultDoc;
}

From source file:com.blocks.framework.utils.date.XMLDom4jUtils.java

License:Open Source License

/**
 * /*from   ww w  .j ava  2  s .c om*/
 * 
 * 
 * 
 * 
 * @param ele
 *            Element
 * @param attributeName
 *            String
 * @return Element
 */
public static Element removeAttribute(Element ele, String attributeName) {
    if (ele == null) {
        return null;
    }

    Attribute att = ele.attribute(attributeName);
    ele.remove(att);
    return ele;
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

/**
* Sets the Schema Location attribute on the root element
*
* @param document The Exchanger document
* @param schemaType The schema type (either schemaLocation or noNamespaceSchemaLocation)
* @param namespace The namespace/*from w  ww.j a  v  a  2 s. com*/
* @param schemaURL The URL or the schema
* 
*/
public static void setSchemaLocation(ExchangerDocument document, String schemaType, String namespace,
        String schemaURL) {
    schemaURL = URLUtilities.encodeURL(schemaURL);

    XDocument xdoc = document.getDocument();
    Element root = xdoc.getRootElement();

    if (schemaType.equals(SCHEMALOCATION)) {
        Attribute attrNoNS = root.attribute(NOSCHEMALOCATION);
        if (attrNoNS != null) {
            root.remove(attrNoNS);
        }

        // need to set both namspace and url
        Attribute attr = root.attribute(SCHEMALOCATION);
        if (attr == null) {
            // does the schema instance already exist
            Namespace ns = root.getNamespaceForURI(SCHEMAINSTANCE);
            if (ns != null) {
                String schemaInstancePrefix = ns.getPrefix();
                StringBuffer name = new StringBuffer();
                name.append(schemaInstancePrefix);
                name.append(":");
                name.append(SCHEMALOCATION);

                StringBuffer value = new StringBuffer();
                value.append(namespace);
                value.append(" ");
                value.append(schemaURL);

                root.addAttribute(name.toString(), value.toString());
            } else {
                root.addNamespace("xsi", SCHEMAINSTANCE);

                StringBuffer name = new StringBuffer();
                name.append("xsi");
                name.append(":");
                name.append(SCHEMALOCATION);

                StringBuffer value = new StringBuffer();
                value.append(namespace);
                value.append(" ");
                value.append(schemaURL);

                root.addAttribute(name.toString(), value.toString());
            }
        } else {
            String attrValue = attr.getValue();

            // break up all the namespace and url pairs
            ArrayList stringValues = new ArrayList();

            StringTokenizer st = new StringTokenizer(attrValue);
            while (st.hasMoreTokens()) {
                stringValues.add(st.nextToken());
            }

            // update existing attribute, Note: it may have multiple attribute pairs
            StringBuffer value = new StringBuffer();
            value.append(namespace);
            value.append(" ");
            value.append(schemaURL);

            //need to start at the third value (i.e we only replace the first namespace-url pair)
            for (int i = 2; i < stringValues.size(); i++) {
                value.append(" ");
                value.append((String) stringValues.get(i));
            }

            attr.setValue(value.toString());
        }
    } else {
        // is of type "no schema location"
        Attribute attrSchema = root.attribute(SCHEMALOCATION);
        if (attrSchema != null) {
            root.remove(attrSchema);
        }

        // just need to set the url
        Attribute attr = root.attribute(NOSCHEMALOCATION);
        if (attr == null) {
            // does the schema instance already exist
            Namespace ns = root.getNamespaceForURI(SCHEMAINSTANCE);
            if (ns != null) {
                String schemaInstancePrefix = ns.getPrefix();
                StringBuffer name = new StringBuffer();
                name.append(schemaInstancePrefix);
                name.append(":");
                name.append(NOSCHEMALOCATION);

                root.addAttribute(name.toString(), schemaURL);
            } else {
                root.addNamespace("xsi", SCHEMAINSTANCE);

                StringBuffer name = new StringBuffer();
                name.append("xsi");
                name.append(":");
                name.append(NOSCHEMALOCATION);

                root.addAttribute(name.toString(), schemaURL);
            }
        } else {
            // update existing attribute
            attr.setValue(schemaURL);
        }
    }
}

From source file:com.cladonia.xngreditor.actions.ToolsConvertNodeAction.java

License:Open Source License

/**
 * add one of various types of node to the xpath - selected nodes
 * //ww w  .j a  v  a2s .  co m
 * @param document
 * @param xpathPredicate
 * @param nodeType
 * @return
 */
public String convertNode(ExchangerDocument document, String xpathPredicate, String nodeType) {

    Vector nodeList = document.search(xpathPredicate);
    Vector attributeList = new Vector();
    String warning = "";
    if (nodeList.size() > 0) {
        try {
            for (int cnt = 0; cnt < nodeList.size(); ++cnt) {
                Node node = (Node) nodeList.get(cnt);
                if (node instanceof Element) {
                    XElement e = (XElement) node;
                    Element parentE = e.getParent();
                    if ((e.hasChildElements()) || (e.attributeCount() > 0)) {
                        if ((e.hasChildElements())) {
                            MessageHandler.showError(parent, "Cannont convert since node has child elements ",
                                    "Tools Convert Node Error");
                            return (null);
                        } else if (e.attributeCount() > 0) {
                            MessageHandler.showError("Cannont convert since node has attributes",
                                    "Tools Convert Node Error");
                            return (null);
                        }
                        cnt = nodeList.size();

                    } else {
                        if (nodeType.equalsIgnoreCase("Element Node")) {
                            MessageHandler.showError(parent, "Node is already an Element",
                                    "Tools Convert Node Error");
                            //end loop
                            cnt = nodeList.size();
                            return (null);
                        } else if (nodeType.equalsIgnoreCase("Attribute Node")) {
                            //check if it has child elements
                            QName qname = e.getQName();
                            //resolve the namespace string
                            parentE.add(new XAttribute(qname, e.getValue()));
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("Text Node")) {
                            FlyweightText newNode = new FlyweightText(e.getText());
                            parentE.add(newNode);
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("CDATA Section Node")) {
                            FlyweightCDATA newNode = new FlyweightCDATA(e.getText());
                            parentE.add(newNode);
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("Processing Instruction Node")) {
                            FlyweightProcessingInstruction newNode = new FlyweightProcessingInstruction(
                                    e.getText(), "");
                            parentE.add(newNode);
                            parentE.remove(e);
                        } else if (nodeType.equalsIgnoreCase("Comment Node")) {
                            FlyweightComment newNode = new FlyweightComment(e.getText());
                            parentE.add(newNode);
                            parentE.remove(e);
                        }
                    }
                } else if (node instanceof Attribute) {
                    XAttribute e = (XAttribute) node;
                    Element parentE = e.getParent();
                    if (nodeType.equalsIgnoreCase("Element Node")) {
                        QName qname = e.getQName();
                        //resolve the namespace string
                        XElement newE = new XElement(qname);
                        parentE.add(newE);
                        newE.setValue(e.getValue());
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("Attribute Node")) {
                        MessageHandler.showError(parent, "Node is already an Attribute",
                                "Tools Convert Node Error");
                        //end loop
                        cnt = nodeList.size();
                        return (null);
                    } else if (nodeType.equalsIgnoreCase("Text Node")) {
                        FlyweightText newNode = new FlyweightText(e.getText());
                        parentE.add(newNode);
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("CDATA Section Node")) {
                        FlyweightCDATA newNode = new FlyweightCDATA(e.getText());
                        parentE.add(newNode);
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("Processing Instruction Node")) {
                        FlyweightProcessingInstruction newNode = new FlyweightProcessingInstruction(e.getText(),
                                "");
                        parentE.add(newNode);
                        parentE.remove(e);
                    } else if (nodeType.equalsIgnoreCase("Comment Node")) {
                        FlyweightComment newNode = new FlyweightComment(e.getText());
                        parentE.add(newNode);
                        parentE.remove(e);
                    }
                } else {
                    //can only handle elements
                    MessageHandler
                            .showError(parent,
                                    "Can only Convert Nodes to elements\n+" + "XPath: " + xpathPredicate
                                            + "refers to a" + node.getNodeTypeName(),
                                    "Tools Convert Node Error");
                    //end for loop
                    cnt = nodeList.size();
                }
            }
        } catch (NullPointerException e) {
            MessageHandler.showError(parent, "XPath: " + xpathPredicate + "\nCannot be resolved",
                    "Tools Convert Node Error");
            return (null);
        } catch (Exception e) {
            MessageHandler.showError(parent, "Error Adding Node", "Tools Convert Node Error");
            return (null);
        }
        document.update();
    } else {
        MessageHandler.showError(parent, "No nodes could be found for:\n" + xpathPredicate,
                "Tools Convert Node Error");
        return (null);
    }
    return (document.getText());
}

From source file:com.cladonia.xngreditor.actions.ToolsMoveNSToFirstUsedAction.java

License:Open Source License

private void removeNamespacesFromElement(Element element) throws Exception {
    List allNamespaces = element.declaredNamespaces();
    for (int cnt = 0; cnt < allNamespaces.size(); ++cnt) {
        element.remove((Namespace) allNamespaces.get(cnt));
    }/*from  ww w.ja v  a2s . c o  m*/
}

From source file:com.cnd.greencube.server.util.dom4j.XmlUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void removeChildren(Element el) {
    for (Iterator<Element> iter = el.elements().iterator(); iter.hasNext();) {
        el.remove(iter.next());
    }/*w  ww .j a  v  a 2 s  .c  om*/
}

From source file:com.ctvit.vdp.services.sysconfiguration.user.UserService.java

public String getRightXML(Map rightIds) throws DocumentException {
    String baseXML = systemConfigDao.selectByPrimaryKey("Rights").getValue();//??XML
    Document doc = DocumentHelper.parseText(baseXML);
    Element baseElement = doc.getRootElement();
    Iterator elementIter = baseElement.elementIterator();
    //?/*from  www  . j  a  v  a  2 s  . c o  m*/
    while (elementIter.hasNext()) {//??
        Element el01 = (Element) elementIter.next();
        if (rightIds.get(el01.attributeValue("id")) == null) {
            baseElement.remove(el01);
        }
        Iterator elIter01 = el01.elementIterator();
        while (elIter01.hasNext()) {//??
            Element el02 = (Element) elIter01.next();
            if (rightIds.get(el02.attributeValue("id")) == null) {
                el01.remove(el02);
            }
            Iterator elIter02 = el02.elementIterator();
            while (elIter02.hasNext()) {//??(?)
                Element el03 = (Element) elIter02.next();
                if (rightIds.get(el03.attributeValue("id")) == null) {
                    el02.remove(el03);
                }

                Iterator elIter03 = el03.elementIterator();
                while (elIter03.hasNext()) {//??()
                    Element el04 = (Element) elIter03.next();
                    if (rightIds.get(el04.attributeValue("id")) == null) {
                        el03.remove(el04);
                    }
                    Iterator elIter04 = el04.elementIterator();
                    while (elIter04.hasNext()) {//??()
                        Element el05 = (Element) elIter04.next();
                        System.out.println(el05.attributeValue("id"));
                        if (rightIds.get(el05.attributeValue("id")) == null) {
                            el04.remove(el05);
                        }
                    }
                }
            }
        }
    }
    return baseElement.asXML();
}

From source file:com.devoteam.srit.xmlloader.core.Scenario.java

License:Open Source License

/**
 * Parse the scenario//from ww  w . j a  v a  2  s .  c  om
 */
private void parse(XMLDocument scenarioDocument) throws Exception {
    //String relativePath = getFilename();

    //XMLDocument scenarioDocument = XMLDocumentCache.getXMLDocument(URIRegistry.MTS_TEST_HOME.resolve(relativePath), URIFactory.newURI("../conf/schemas/scenario.xsd"));

    Element root = scenarioDocument.getDocument().getRootElement();

    /**
     * Check the position of the finally tag
     */
    boolean isFinallyLast = false;
    int finallyInstances = 0;
    List<Element> elements = root.elements();
    for (Element element : elements) {
        isFinallyLast = false;
        if (element.getName().equals("finally")) {
            isFinallyLast = true;
            finallyInstances++;
        }
    }

    if (finallyInstances == 1 && !isFinallyLast) {
        throw new ParsingException("Finally must be the last operation of the scenario.");
    } else if (finallyInstances > 1) {
        throw new ParsingException("There must be at most one finally operation.");
    }

    /**
     * Create the finally operations sequence. If there is a finally then the sequence is created and then the finally tag is removed from the scenario. To allow the creation of the scenario
     * operations sequence.
     */
    if (finallyInstances == 1) {
        Element finallyRoot = root.element("finally");
        root.remove(finallyRoot);
        this._operationSequenceFinally = new OperationSequence(finallyRoot, this);
    }

    _operationSequenceScenario = new OperationSequence(root, this);
}