Example usage for org.jdom2 Element removeContent

List of usage examples for org.jdom2 Element removeContent

Introduction

In this page you can find the example usage for org.jdom2 Element removeContent.

Prototype

@Override
    public Content removeContent(final int index) 

Source Link

Usage

From source file:arquivo.Arquivo.java

public String remove(String nome, String nomeE) {
    SAXBuilder builder = new SAXBuilder();
    List<Element> retorna = new LinkedList<>();

    try {//w w  w  .  jav  a 2s .  c  o  m
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        List<Element> removido = buscaInterna(root, true, nome, nomeE);
        root.removeContent(removido.get(0));

        XMLOutputter xout = new XMLOutputter();
        OutputStream out = new FileOutputStream(arquivo);
        xout.output(doc, out);
        return "Documento alterado com sucesso!";
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "n foi possivel remover " + nome;
}

From source file:codigoFonte.Sistema.java

public boolean removeUser(User u) {
    File file = new File("Sistema.xml");
    Document newDocument = null;//from   w  w w .j a v a  2s. c o  m
    Element root = null;
    Element user = null;
    boolean success = false;

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    } else {
        root = new Element("sistema");

        newDocument = new Document(root);
    }

    List<Element> listusers = root.getChildren("user");
    for (Element e : listusers) {
        if (e.getAttributeValue("matrcula").equals(u.getMatricula()) && e.getChildren("livro").size() == 0) {
            root.removeContent(e);

            XMLOutputter out = new XMLOutputter();

            try {
                FileWriter arquivo = new FileWriter(file);
                out.output(newDocument, arquivo);
            } catch (IOException ex) {
                Logger.getLogger(Sistema.class.getName()).log(Level.SEVERE, null, ex);
            }

            success = true;
            return success;
        }
    }
    return success;
}

From source file:com.rometools.modules.sle.io.ItemParser.java

License:Apache License

/**
 * Parses the XML node (JDOM element) extracting module information.
 * <p>//from www .  ja v a  2s.  c  o m
 *
 * @param element the XML node (JDOM element) to extract module information from.
 * @return a module instance, <b>null</b> if the element did not have module information.
 */
@Override
public Module parse(final Element element, final Locale locale) {
    final SleEntryImpl sle = new SleEntryImpl();
    ArrayList<EntryValue> values = new ArrayList<EntryValue>();
    final List<Element> groups = element.getChildren("group", ModuleParser.TEMP);

    for (final Element group : groups) {
        final StringValue value = new StringValue();
        value.setElement(group.getAttributeValue("element"));
        value.setLabel(group.getAttributeValue("label"));
        value.setValue(group.getAttributeValue("value"));
        if (group.getAttributeValue("ns") != null) {
            value.setNamespace(Namespace.getNamespace(group.getAttributeValue("ns")));
        } else {
            value.setNamespace(element.getDocument().getRootElement().getNamespace());
        }
        values.add(value);
        element.removeContent(group);
    }

    sle.setGroupValues(values.toArray(new EntryValue[values.size()]));
    values = values.size() == 0 ? values : new ArrayList<EntryValue>();

    final List<Element> sorts = new ArrayList<Element>(element.getChildren("sort", ModuleParser.TEMP));
    // LOG.debug("]]] sorts on element"+sorts.size());
    for (final Element sort : sorts) {
        final String dataType = sort.getAttributeValue("data-type");
        // LOG.debug("Doing datatype "+dataType +" :: "+sorts.size());
        if (dataType == null || dataType.equals(Sort.TEXT_TYPE)) {
            final StringValue value = new StringValue();
            value.setElement(sort.getAttributeValue("element"));
            value.setLabel(sort.getAttributeValue("label"));
            value.setValue(sort.getAttributeValue("value"));
            if (sort.getAttributeValue("ns") != null) {
                value.setNamespace(Namespace.getNamespace(sort.getAttributeValue("ns")));
            } else {
                value.setNamespace(element.getDocument().getRootElement().getNamespace());
            }
            values.add(value);

            element.removeContent(sort);

        } else if (dataType.equals(Sort.DATE_TYPE)) {
            final DateValue value = new DateValue();
            value.setElement(sort.getAttributeValue("element"));
            value.setLabel(sort.getAttributeValue("label"));
            if (sort.getAttributeValue("ns") != null) {
                value.setNamespace(Namespace.getNamespace(sort.getAttributeValue("ns")));
            } else {
                value.setNamespace(element.getDocument().getRootElement().getNamespace());
            }
            Date dateValue = null;

            try {
                dateValue = DateParser.parseRFC822(sort.getAttributeValue("value"), locale);
                if (dateValue == null) {
                    dateValue = DateParser.parseW3CDateTime(sort.getAttributeValue("value"), locale);
                }
            } catch (final Exception e) {
                ; // ignore parse exceptions
            }

            value.setValue(dateValue);
            values.add(value);
            element.removeContent(sort);
        } else if (dataType.equals(Sort.NUMBER_TYPE)) {
            final NumberValue value = new NumberValue();
            value.setElement(sort.getAttributeValue("element"));
            value.setLabel(sort.getAttributeValue("label"));
            if (sort.getAttributeValue("ns") != null) {
                value.setNamespace(Namespace.getNamespace(sort.getAttributeValue("ns")));
            } else {
                value.setNamespace(element.getDocument().getRootElement().getNamespace());
            }

            try {
                value.setValue(new BigDecimal(sort.getAttributeValue("value")));
            } catch (final NumberFormatException nfe) {
                ; // ignore
                values.add(value);
                element.removeContent(sort);
            }
        } else {
            throw new RuntimeException("Unknown datatype");
        }
    }
    // LOG.debug("Values created "+values.size()+" from sorts" +sorts.size());
    sle.setSortValues(values.toArray(new EntryValue[values.size()]));

    return sle;
}

From source file:com.tactfactory.harmony.generator.androidxml.ManifestUpdater.java

License:Open Source License

/**
 * Remove the launcher category from the intent filter 
 * of the given activity.//from  w  ww.j a  v a 2s.  c  om
 * 
 * @param activityName The activity to remove the launcher category from
 */
public void removeLauncherIntentFilter(String activityName) {
    // Load Root element
    final Element rootNode = this.getDocument().getRootElement();

    // Load Name space (required for manipulate attributes)
    final Namespace ns = rootNode.getNamespace(ManifestConstants.NAMESPACE_ANDROID);

    Element activity = this.findActivityNamed(activityName, ns);
    Element foundCategory = null;
    List<Element> intentFilters = activity.getChildren(ManifestConstants.ELEMENT_INTENT_FILTER);

    if (intentFilters != null) {
        for (Element intentFilter : intentFilters) {
            List<Element> categories = intentFilter.getChildren(ManifestConstants.ELEMENT_CATEGORY);

            if (categories != null) {
                for (Element category : categories) {
                    String categoryName = category.getAttributeValue(ManifestConstants.ATTRIBUTE_NAME, ns);
                    if ("android.intent.category.LAUNCHER".equals(categoryName)) {
                        foundCategory = category;
                    }
                }

                if (foundCategory != null) {
                    intentFilter.removeContent(foundCategory);
                }
            }
        }
    }
}

From source file:com.tactfactory.harmony.platform.winphone.updater.XmlProjectWinphone.java

License:Open Source License

private void removeIfExists(Element element, String type, String file) {
    Filter<Element> filter = new ElementFilter(type);
    List<Element> content = element.getContent(filter);
    List<Element> elementToDelete = new ArrayList<>();

    for (Element node : content) {
        if (node.getAttribute("Include").getValue().equals(file)) {
            elementToDelete.add(node);//  ww w . ja v a  2 s.c  o m
        }
    }

    for (Element node : elementToDelete) {
        element.removeContent(node);
    }
}

From source file:de.danielluedecke.zettelkasten.database.Bookmarks.java

License:Open Source License

/**
 * This method deletes a category from the data file. The category that should be deleted
 * is indicated by the category's index-number, passed as parameter "nr". If the index-number
 * is not known, use {@link #deleteCategory(java.lang.String) deleteCategory(String cat)} to delete that 
 * category or {@link #getCategoryPosition getCategoryPosition(int nr)} to retrieve that number.
 * <br><br>/*from w w  w . j a  v a2  s.co  m*/
 * <b>Attention!</b> All related bookmarks that are assigned to this category are deleted as well!
 * 
 * @param nr the index-number of the to be deleted category.
 */
public void deleteCategory(int nr) {
    // get cat-element
    Element category = bookmarks.getRootElement().getChild("category");
    // delete category from the xml-file
    if (category != null && category.removeContent(nr) != null) {
        // if we have successfully deleted a category, delete all bookmarks from
        // that category as well
        for (int cnt = getCount() - 1; cnt >= 0; cnt--) {
            // get each bookmark
            Element bm = retrieveBookmarkElement(cnt);
            try {
                // get category-atribute
                String cat = bm.getAttributeValue("cat");
                // check whether attribute exists
                if (cat != null) {
                    // get cat id
                    int catid = Integer.parseInt(cat);
                    // if catid equals the deleted category, delete bookmark
                    if (catid == nr) {
                        // get bookmark-element
                        Element child = bookmarks.getRootElement().getChild("bookmark");
                        // if it exists, remove it
                        if (child != null) {
                            child.removeContent(cnt);
                        }
                    }
                    // in case the category-id was greater than the deleted category index-number,
                    // we have to update the category-index-number of the non-deleted bookmark
                    else if (catid > nr) {
                        bm.setAttribute("cat", String.valueOf(catid - 1));
                    }
                }
            } catch (NumberFormatException e) {
                Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
            } catch (IllegalNameException e) {
                Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
            } catch (IllegalDataException e) {
                Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
            }
            // change modified state
            setModified(true);
        }
    }
}

From source file:de.danielluedecke.zettelkasten.database.DesktopData.java

License:Open Source License

/**
 * This method moves an element (entry-node or bullet-point) one position up- or downwards, depending
 * on the parameter {@code movement}./*from  w ww  .j av a 2s .c  o m*/
 * @param movement indicates whether the element should be moved up or down. use following constants:<br>
 * - {@code CConstants.MOVE_UP}<br>
 * - {@code CConstants.MOVE_DOWN}<br>
 * @param timestamp
 */
public void moveElement(int movement, String timestamp) {
    // get the selected element, independent from whether it's a node or a bullet
    Element e = findEntryElementFromTimestamp(getCurrentDesktopElement(), timestamp);
    if (e != null) {
        // get the element's parent
        Element p = e.getParentElement();
        // get the index of the element that should be moved
        int index = p.indexOf(e);
        // remove the element that should be moved
        Element dummy = (Element) p.removeContent(index);
        try {
            // and insert element one index-position below the previous index-position
            p.addContent((Constants.MOVE_UP == movement) ? index - 1 : index + 1, dummy);
            // change modifed state
            setModified(true);
        } catch (IllegalAddException ex) {
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
        }
    }
}

From source file:edu.unc.lib.dl.xml.DepartmentOntologyUtil.java

License:Apache License

/**
 * Compares the affiliation values in the given MODS document against the ontology. If a preferred term(s) is found,
 * then it will replace the original. Only the first and last terms in a single hierarchy are kept if there are more
 * than two levels//  w  w  w  .ja v a2 s  .  co m
 *
 * @param modsDoc
 * @return Returns true if the mods document was modified by adding or changing affiliations
 * @throws JDOMException
 */
@Override
public boolean updateDocumentTerms(Element docElement) throws JDOMException {
    List<?> nameObjs = namePath.evaluate(docElement);
    boolean modified = false;

    for (Object nameObj : nameObjs) {
        Element nameEl = (Element) nameObj;

        List<?> affiliationObjs = nameEl.getChildren("affiliation", MODS_V3_NS);
        if (affiliationObjs.size() == 0)
            continue;

        // Collect the set of all affiliations for this name so that it can be used to detect duplicates
        Set<String> affiliationSet = new HashSet<>();
        for (Object affiliationObj : affiliationObjs) {
            Element affiliationEl = (Element) affiliationObj;

            affiliationSet.add(affiliationEl.getTextNormalize());
        }

        // Make a snapshot of the list of affiliations so that the original can be modified
        List<?> affilList = new ArrayList<>(affiliationObjs);
        // Get the authoritative department path for each affiliation and overwrite the original
        for (Object affiliationObj : affilList) {
            Element affiliationEl = (Element) affiliationObj;
            String affiliation = affiliationEl.getTextNormalize();

            List<List<String>> departments = getAuthoritativeForm(affiliation);
            if (departments != null && departments.size() > 0) {

                Element parentEl = affiliationEl.getParentElement();
                int affilIndex = parentEl.indexOf(affiliationEl);

                boolean removeOriginal = true;
                // Add each path that matched the affiliation. There can be multiple if there were multiple parents
                for (List<String> deptPath : departments) {
                    String baseDept = deptPath.size() > 1 ? deptPath.get(0) : null;
                    String topDept = deptPath.get(deptPath.size() - 1);

                    // No need to remove the original if it is in the set of departments being added
                    if (affiliation.equals(topDept))
                        removeOriginal = false;

                    modified = addAffiliation(baseDept, parentEl, affilIndex, affiliationSet) || modified;
                    modified = addAffiliation(topDept, parentEl, affilIndex, affiliationSet) || modified;
                }

                // Remove the old affiliation unless it was already in the vocabulary
                if (removeOriginal)
                    parentEl.removeContent(affiliationEl);

            }
        }
    }

    return modified;
}

From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java

License:Apache License

private void processComment(final Comment comment, final Element at, final Slide slide,
        final Configuration configuration) throws JODTemplateException {
    String commentText = comment.getText();
    if (commentText.startsWith(STYLIZED_KEYWORD)) {
        commentText = StringUtils.removeStart(commentText, STYLIZED_KEYWORD);
        final String className = StringUtils.substringBefore(commentText, ":");
        commentText = StringUtils.removeStart(commentText, className + ": ");
        final Stylizer stylizer = configuration.getStylizer(className);
        if (stylizer == null) {
            throw new JODTemplateException("Unable to find stylizer");
        }//  w ww  .  j  a  va2  s  .c om
        final String text = StringUtils.removeStart(commentText, " stylized: ");
        final Element ar = at.getParentElement();
        final Element ap = ar.getParentElement();
        final int arIndex = ap.indexOf(ar);
        final Element arPr = getArPrElement(ar);
        final Element apPr = getApPrElement(ap);
        final Element sourceApPr = ObjectUtils.clone(apPr);
        cleanApPrElement(apPr);

        final List<Element> stylizedElements = stylizer.stylize(text, arPr, apPr, slide);

        ap.removeContent(ar);
        final List<Element> remains = getRemainingElements(arIndex, ap);
        for (Element el : remains) {
            ap.removeContent(el);
        }

        final int currentApIndex = injectElementsInDocument(stylizedElements, ap, apPr, arIndex);
        injectRemainsInDocument(remains, ap, sourceApPr, currentApIndex);
    }
}

From source file:org.apache.maven.io.util.WriterUtils.java

License:Apache License

/**
 * Method updateElement./* ww  w .  j  a  v  a2s. c o m*/
 * 
 * @param counter
 * @param shouldExist
 * @param name
 * @param parent
 * @return Element
 */
public static Element updateElement(final IndentationCounter counter, final Element parent, final String name,
        final boolean shouldExist) {
    Element element = parent.getChild(name, parent.getNamespace());
    if (shouldExist) {
        if (element == null) {
            element = factory.element(name, parent.getNamespace());
            insertAtPreferredLocation(parent, element, counter);
        }
        counter.increaseCount();
    } else if (element != null) {
        final int index = parent.indexOf(element);
        if (index > 0) {
            final Content previous = parent.getContent(index - 1);
            if (previous instanceof Text) {
                final Text txt = (Text) previous;
                if (txt.getTextTrim().length() == 0) {
                    parent.removeContent(txt);
                }
            }
        }
        parent.removeContent(element);
    }
    return element;
}