Example usage for org.jdom2 Element setText

List of usage examples for org.jdom2 Element setText

Introduction

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

Prototype

public Element setText(final String text) 

Source Link

Document

Sets the content of the element to be the text given.

Usage

From source file:interfacermi.Traza.java

public void insertarTraza(String hora, String actor, String accion) {

    Document document = null;/*from  www .  ja v  a 2  s .  co m*/
    Element root = null;
    File xmlFile = new File("Traza.xml");
    //Se comprueba si el archivo XML ya existe o no.
    if (xmlFile.exists()) {
        FileInputStream fis;
        try {
            fis = new FileInputStream(xmlFile);
            SAXBuilder sb = new SAXBuilder();
            document = sb.build(fis);
            //Si existe se obtiene su nodo raiz.
            root = document.getRootElement();
            fis.close();
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    } else {
        //Si no existe se crea su nodo raz.
        document = new Document();
        root = new Element("Traza");
    }

    //Se crea un nodo Hecho para insertar la informacin.
    Element nodohecho = new Element("Hecho");
    //Se crea un nodo hora para insertar la informacin correspondiente a la hora.
    Element nodohora = new Element("Hora");
    //Se crea un nodo actor para insertar la informacin correspondiente al actor.
    Element nodoactor = new Element("Actor");
    //Se crea un nodo accion para insertar la informacin correspondiente a la accin.
    Element nodoaccion = new Element("Accion");

    //Se asignan los valores enviados para cada nodo.
    nodohora.setText(hora);
    nodoactor.setText(actor);
    nodoaccion.setText(accion);
    //Se aade el contenido al nodo Hecho.  
    nodohecho.addContent(nodohora);
    nodohecho.addContent(nodoactor);
    nodohecho.addContent(nodoaccion);
    //Se aade el nodo Hecho al nodo raz.
    root.addContent(nodohecho);
    document.setContent(root);

    //Se procede a exportar el nuevo o actualizado archivo de traza XML   
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());

    try {
        xmlOutput.output(document, new FileWriter("Traza.xml"));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

License:Apache License

/**
 * Checks if the given element has to be rewritten.
 * Is called for every child single element of the parent given to rewriteContent method.
 * @param element Element to check/*from  w ww  . j  av  a2s.co  m*/
 * @return null if nothing is to do with this element.
 *         Return empty list to remove this element.
 *         Return list with other content to replace element with new content.
 */
@Override
public List<Content> rewriteElement(Element element) {

    // rewrite anchor elements
    if (StringUtils.equalsIgnoreCase(element.getName(), "a")) {
        return rewriteAnchor(element);
    }

    // rewrite image elements
    else if (StringUtils.equalsIgnoreCase(element.getName(), "img")) {
        return rewriteImage(element);
    }

    // detect BR elements and turn those into "self-closing" elements
    // since the otherwise generated <br> </br> structures are illegal and
    // are not handled correctly by Internet Explorers
    else if (StringUtils.equalsIgnoreCase(element.getName(), "br")) {
        if (element.getContent().size() > 0) {
            element.removeContent();
        }
        return null;
    }

    // detect empty elements and insert at least an empty string to avoid "self-closing" elements
    // that are not handled correctly by most browsers
    else if (NONSELFCLOSING_TAGS.contains(StringUtils.lowerCase(element.getName()))) {
        if (element.getContent().isEmpty()) {
            element.setText("");
        }
        return null;
    }

    return null;
}

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

License:Apache License

/**
 * Checks if the given anchor element has to be rewritten.
 * @param element Element to check//from ww  w.j  a v a2  s  .  c  o  m
 * @return null if nothing is to do with this element.
 *         Return empty list to remove this element.
 *         Return list with other content to replace element with new content.
 */
private List<Content> rewriteAnchor(Element element) {

    // detect empty anchor elements and insert at least an empty string to avoid "self-closing" elements
    // that are not handled correctly by most browsers
    if (element.getContent().isEmpty()) {
        element.setText("");
    }

    // resolve link metadata from DOM element
    Link link = getAnchorLink(element);

    // build anchor for link metadata
    Element anchorElement = buildAnchorElement(link, element);

    // Replace anchor tag or remove anchor tag if invalid - add any sub-content in every case
    List<Content> content = new ArrayList<Content>();
    if (anchorElement != null) {
        anchorElement.addContent(element.cloneContent());
        content.add(anchorElement);
    } else {
        content.addAll(element.getContent());
    }
    return content;
}

From source file:jcodecollector.io.PackageManager.java

License:Apache License

public static boolean exportSnippets(File file, String category) {
    ArrayList<Snippet> array = null;

    if (category == null) {
        array = DBMS.getInstance().getAllSnippets();
    } else {//w  w w  . ja v a2s .  c o  m
        array = DBMS.getInstance().getSnippets(category);
    }

    Element root = new Element("jcc-snippets-package");
    root.setAttribute("version", GeneralInfo.APPLICATION_VERSION);

    Iterator<Snippet> iterator = array.iterator();
    while (iterator.hasNext()) {
        Snippet snippet = iterator.next();
        Element element = new Element("snippet");

        Element category_xml = new Element("category");
        category_xml.setText(snippet.getCategory());
        element.addContent(category_xml);

        Element name_xml = new Element("name");
        name_xml.setText(snippet.getName());
        element.addContent(name_xml);

        String[] tags = snippet.getTags();
        for (String tag : tags) {
            Element tag_xml = new Element("tag");
            tag_xml.setText(tag);
            element.addContent(tag_xml);
        }

        Element syntax_xml = new Element("syntax");
        syntax_xml.setText(snippet.getSyntax());
        element.addContent(syntax_xml);

        Element code_xml = new Element("code");
        code_xml.setText(snippet.getCode());
        element.addContent(code_xml);

        Element comment_xml = new Element("comment");
        comment_xml.setText(snippet.getComment());
        element.addContent(comment_xml);

        root.addContent(element);
    }

    try {
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        outputter.output(new Document(root), new FileOutputStream(file));
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

From source file:jcodecollector.io.XMLManagerOldVersion.java

License:Apache License

public static boolean createPackage(File file, String name) {
    ArrayList<Snippet> array = DBMS.getInstance().getSnippets(name);
    Element root_xml = new Element("jcc-snippets-package");
    boolean success;

    Iterator<Snippet> iterator = array.iterator();
    while (iterator.hasNext()) {
        Snippet snippet = iterator.next();
        Element element = new Element("snippet");

        Element category_xml = new Element("category");
        category_xml.setText(snippet.getCategory());
        element.addContent(category_xml);

        Element name_xml = new Element("name");
        name_xml.setText(snippet.getName());
        element.addContent(name_xml);/*from   w w w .j  a v a  2  s.c  o m*/

        String[] tags = snippet.getTags();
        for (String tag : tags) {
            Element tag_xml = new Element("tag");
            tag_xml.setText(tag);
            element.addContent(tag_xml);
        }

        Element syntax_xml = new Element("syntax");
        syntax_xml.setText(snippet.getSyntax());
        element.addContent(syntax_xml);

        Element code_xml = new Element("code");
        code_xml.setText(snippet.getCode());
        element.addContent(code_xml);

        Element comment_xml = new Element("comment");
        comment_xml.setText(snippet.getComment());
        element.addContent(comment_xml);

        Element locked_xml = new Element("locked");
        locked_xml.setText(String.valueOf(snippet.isLocked()));
        element.addContent(locked_xml);

        root_xml.addContent(element);
    }

    try {
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        outputter.output(new Document(root_xml), new FileOutputStream(file));

        success = true;
    } catch (Exception ex) {
        ex.printStackTrace();
        success = false;
    }

    return success;
}

From source file:jmri.jmrit.vsdecoder.VSDecoderPreferences.java

License:Open Source License

private org.jdom2.Element store() {
    org.jdom2.Element ec;
    org.jdom2.Element e = new org.jdom2.Element("VSDecoderPreferences");
    e.setAttribute("isAutoStartingEngine", "" + isAutoStartingEngine());
    e.setAttribute("isAutoLoadingDefaultVSDFile", "" + isAutoLoadingDefaultVSDFile());
    ec = new Element("DefaultVSDFilePath");
    ec.setText("" + getDefaultVSDFilePath());
    e.addContent(ec);//from  w  ww  .  ja va 2s  .c  o  m
    ec = new Element("DefaultVSDFileName");
    ec.setText("" + getDefaultVSDFileName());
    e.addContent(ec);
    // ListenerPosition generates its own XML
    e.addContent(_listenerPosition.getXml("ListenerPosition"));
    ec = new Element("AudioMode");
    ec.setText("" + AudioModeMap.get(_audioMode));
    e.addContent(ec);
    return e;
}

From source file:jodtemplate.pptx.preprocessor.ShortListPreprocessor.java

License:Apache License

@Override
public Document process(final Map<String, Object> context, final Document document, final Slide slide,
        final Resources resources, final Configuration configuration) throws JODTemplateException {
    final IteratorIterable<Element> parentElements = document
            .getDescendants(Filters.element(parentElement, getNamespace()));
    final List<Element> parentElementsList = new ArrayList<>();
    while (parentElements.hasNext()) {
        parentElementsList.add(parentElements.next());
    }/*from   w ww  . ja  v a  2  s . c o  m*/

    for (final Element parent : parentElementsList) {
        final IteratorIterable<Element> atElements = parent
                .getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace()));
        final List<Element> atElementsList = new ArrayList<>();
        while (atElements.hasNext()) {
            atElementsList.add(atElements.next());
        }

        final ExpressionHandler expressionHandler = configuration.getExpressionHandler();
        boolean isLoop = false;
        InlineListExpression expression = null;
        for (final Element at : atElementsList) {
            final String text = at.getText();
            if (configuration.getExpressionHandler().isInlineList(text)) {
                expression = expressionHandler.createInlineListExpression(text);
                at.setText(expressionHandler.createVariable(expression.getVariable()));
                isLoop = true;
            }
        }
        if (isLoop) {
            int apIndex = parent.getParent().indexOf(parent);
            final String beginList = expressionHandler.createBeginList(expression.getWhat(),
                    expression.getAs());
            final String endList = expressionHandler.createEndList();
            parent.getParent().addContent(apIndex, new Comment(beginList));
            apIndex++;
            parent.getParent().addContent(apIndex + 1, new Comment(endList));
        }
    }
    return document;
}

From source file:jodtemplate.pptx.style.HtmlStylizer.java

License:Apache License

private Element createTextElement(final List<org.jsoup.nodes.Element> tags, final Element arPr,
        final TextNode textNode, final Slide slide) {
    final Element ar = new Element(PPTXDocument.R_ELEMENT, getDrawingmlNamespace());
    final Element formattedArPr = applyFormatting(tags, arPr, slide);
    if (formattedArPr.hasAttributes() || formattedArPr.getContentSize() != 0) {
        ar.addContent(formattedArPr);/*www  . j a  v  a  2  s. c om*/
    }
    final Element at = new Element(PPTXDocument.T_ELEMENT, getDrawingmlNamespace());
    at.setText(textNode.getWholeText());
    ar.addContent(at);
    return ar;
}

From source file:jworkspace.ui.plaf.XPlafConnector.java

License:Open Source License

/**
 * Writes the current state of connector to jdom element
 * <p>/*  w  w w .j  a v  a 2s.c o m*/
 * Example element:
 * <plaf name="Kinststoff">
 * <class>com.incors.plaf.kunststoff.KunststoffLookAndFeel</class>
 * <theme current="false">com.incors.plaf.kunststoff.themes.KunststoffDesktopTheme</theme>
 * <theme current="true">com.incors.plaf.kunststoff.themes.KunststoffNotebookTheme</theme>
 * <theme current="false">com.incors.plaf.kunststoff.themes.KunststoffPresentationTheme</theme>
 * <method access="public" static="true" type="void" name="setCurrentTheme"/>
 * </plaf>
 *
 * @return jdom element
 */
Element serialize() {
    /*
     * Root
     */
    Element plaf = new Element("plaf");
    plaf.setAttribute(NAME_ATTRIBUTE, info.getName());
    /*
     * Class
     */
    Element clazz = new Element(CLASS_NODE);
    clazz.setText(info.getClassName());
    plaf.addContent(clazz);

    if (themes != null) {
        for (MetalTheme metalTheme : themes) {
            Element theme = new Element(THEME_NODE);
            theme.setText(metalTheme.getClass().getName());
            plaf.addContent(theme);
        }
    }

    if (method != null) {
        plaf.addContent(method.detach());
    }
    return plaf;
}

From source file:lu.list.itis.dkd.assess.cloze.template.ClozeItem.java

License:Apache License

/**
 * Returns the cloze item block element for the template, which is based on
 * qti structure.//from  w w  w. j  a va2  s .c o  m
 * 
 * @return
 */
public Element getClozeBlock() {
    final Element p = new Element("p");
    for (final ClozeSentence clozeSentence : clozeSentences) {
        String temp = clozeSentence.getContent();

        // Serach gap(s) in the clozeSentene.
        final Pattern gapPattern = Pattern.compile("___[0-9]+___");
        final Matcher gapMatcher = gapPattern.matcher(temp);

        while (gapMatcher.find()) {
            // Find gap and transform it into a number
            final String gap = gapMatcher.group(0);
            int identifierIndex = Integer.parseInt(gap.replace("_", "")) - 1;

            // Cut sentence until gap
            final int begin = temp.indexOf(gap);
            final int end = temp.indexOf(gap) + gap.length();

            final String sentencePart = temp.substring(0, begin);
            temp = temp.substring(end, temp.length());
            p.addContent(sentencePart);

            // Create QTI inlineChoiceInteraction block from gap
            final Gap qtiGap = gaps.get(identifierIndex);
            final Element inlineChoiceInteraction = new Element("inlineChoiceInteraction");
            inlineChoiceInteraction.setAttribute("responseIdentifier", "RESPONSE" + (identifierIndex + 1));
            inlineChoiceInteraction.setAttribute("shuffle", "true");
            p.addContent(inlineChoiceInteraction);

            final Element keyInlineChoice = new Element("inlineChoice");
            keyInlineChoice.setAttribute("identifier", qtiGap.getKey().getKeyWord().getContent() + "1");
            keyInlineChoice.setText(qtiGap.getKey().getKeyWord().getContent());
            inlineChoiceInteraction.addContent(keyInlineChoice);

            int optionIndex = 2;
            for (final Distractor distractor : qtiGap.getDistractors()) {
                final String distractorValue = distractor.getDistractorWord().getContent();
                final Element distractorInlineChoice = new Element("inlineChoice");
                distractorInlineChoice.setAttribute("identifier",
                        qtiGap.getKey().getKeyWord().getContent() + optionIndex);
                distractorInlineChoice.setText(distractorValue);
                inlineChoiceInteraction.addContent(distractorInlineChoice);
                optionIndex++;
            }
        }

        // Add rest of text
        p.addContent(temp);
    }

    return p;
}