Java Code Examples for org.jdom2.Element#setText()

The following examples show how to use org.jdom2.Element#setText() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/*********************************************************************/

    public static void main(String args[]) {
        // unit testing
        //  String s = "(Name = JOHN)";
        String s = "-50 > 20";
        Element e = new Element("testElement");
        e.setAttribute("nval", "17") ;
        e.setAttribute("sval", "\"apples\"") ;
        e.setAttribute("bval", "true") ;
        Element d = new Element("Age");
        d.setText("30");
        e.addContent(d) ;

        ConditionEvaluator t = new ConditionEvaluator();

        try {
            //		    t.p(t.evalExpression("27", "!=", "26")) ;
           // s = "cost(case()) > 5";
            s = "1 = (1";
            boolean b = t.evaluate(s, e) ;
            t.p("expression: " + s + ", returns: " + b) ;
        }
        catch ( RdrConditionException re) { re.printStackTrace() ;}

    }
 
Example 2
/**
 * Sets the comment of the selected entry in the jTree in the
 * CDesktop-frame. This method traverses the xml-datafile, looking in each
 * "depth-level" for the element that is given in the linked list parameter
 * <i>tp</i>. This parameter contains the treepath to the selected element.
 *
 * @param timestamp
 * @param comment a string containing the comment
 * @return {@code true} if comment was successfully set, {@code false} if an
 * error occured.
 */
public boolean setComment(String timestamp, String comment) {
    // retrieve element that matches the timestamp
    Element e = findEntryElementFromTimestamp(getCurrentDesktopElement(), timestamp);
    // check whether an entry was found or not
    if (e != null) {
        try {
            // check whether we have a bullet-point
            if (e.getName().equals(ELEMENT_BULLET)) {
                // if we have a bullet, return the text of it's comment-child.
                e.getChild(ATTR_COMMENT).setText(comment);
            } else {
                // set comment for entry
                e.setText(comment);
            }
            // change modified state
            setModified(true);
        } catch (IllegalDataException ex) {
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
            return false;
        }
    }
    return true;
}
 
Example 3
public void addSynonym(String[] synline) {
    // we need at least two elements in the array: the original word and at least one synonym
    if (null == synline || synline.length < 2) {
        return;
    }
    // if the synonyms-index-word already exists, don't add it...
    if (getSynonymPosition(synline[0]) != -1) {
        return;
    }
    // create new synonyms element
    Element synonym = new Element(Daten.ELEMENT_ENTRY);
    try {
        // trim spaces
        synline[0] = synline[0].trim();
        // set the original word as value-attribute to the "entry"-element
        synonym.setAttribute("indexword", synline[0]);
        // now go through the rest of the string-array
        for (int cnt = 1; cnt < synline.length; cnt++) {
            // create a sub-child "syn" for each further synonym
            Element syn = new Element("syn");
            // set text from string array
            syn.setText(synline[cnt].trim());
            // add child to synonym-element
            synonym.addContent(syn);
        }
        // finally, add new element to the document
        synonymsFile.getRootElement().addContent(synonym);
        setModified(true);
    } catch (IllegalNameException | IllegalDataException | IllegalAddException ex) {
        Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage());
    }
}
 
Example 4
private boolean replace(Document xml, String key, String text) throws IOException {
    for (Element e : (List<Element>) xml.getRootElement().getChildren()) {
        String k = e.getAttributeValue("name");
        if (k.equals(key)) {
            if (e.getText().trim().equals(text.trim())) {
                return false;
            } else {
                e.setText(text);
                return true;
            }
        }
    }
    throw new IOException("key " + key + " not found in " + xml);
}
 
Example 5
/**
 * Creates a new element with the same name and attributes as the old one
 * @param element the elment to clone
 * @param defNS the default namespace
 * @return the cloned element
 */
private Element cloneElement(Element element, Namespace defNS) {
    Element cloned = new Element(element.getName(), defNS);
    cloned.setAttributes(cloneAttributes(element, defNS));

    // clone appinfo children literally
    Element parent = element.getParentElement();
    if (parent != null && parent.getName().equals("appinfo")) {
        cloned.setText(element.getText());
    }
    return cloned;
}
 
Example 6
protected Element viewInterestPointsToXml( final InterestPointList interestPointList, final int tpId, final int viewId, final String label )
{
	final Element elem = new Element( VIEWINTERESTPOINTSFILE_TAG );
	elem.setAttribute( VIEWINTERESTPOINTS_TIMEPOINT_ATTRIBUTE_NAME, Integer.toString( tpId ) );
	elem.setAttribute( VIEWINTERESTPOINTS_SETUP_ATTRIBUTE_NAME, Integer.toString( viewId ) );
	elem.setAttribute( VIEWINTERESTPOINTS_LABEL_ATTRIBUTE_NAME, label );
	elem.setAttribute( VIEWINTERESTPOINTS_PARAMETERS_ATTRIBUTE_NAME, interestPointList.getParameters() );
	// a hack so that windows does not put its backslashes in
	elem.setText( interestPointList.getFile().toString().replace( "\\", "/" ) );

	return elem;
}
 
Example 7
private static void addTableRow(final Element table, final String[] cells) {
    final Element tr = new Element("tr");
    table.addContent(tr);
    for (final String columnName : cells) {
        final Element td = new Element("td");
        tr.addContent(td);
        td.setText(columnName);
    }
}
 
Example 8
public Element toXml()
{
    final Element answerElement = new Element( ChaiResponseSet.XML_NODE_ANSWER_VALUE );
    answerElement.setText( answerHash );
    answerElement.setAttribute( ChaiResponseSet.XML_ATTRIBUTE_CONTENT_FORMAT, formatType.toString() );
    return answerElement;
}
 
Example 9
public static MCRChangeData setText(Element element, String text) {
    Element clone = element.clone();

    for (Iterator<Attribute> attributes = clone.getAttributes().iterator(); attributes.hasNext();) {
        attributes.next();
        attributes.remove();
    }

    MCRChangeData data = new MCRChangeData("set-text", clone, 0, element);
    element.setText(text);
    return data;
}
 
Example 10
public Element toXml()
{
    final Element answerElement = new Element( ChaiResponseSet.XML_NODE_ANSWER_VALUE );
    answerElement.setText( version.toString() + VERSION_SEPARATOR + answerHash );
    if ( salt != null && salt.length() > 0 )
    {
        answerElement.setAttribute( ChaiResponseSet.XML_ATTRIBUTE_SALT, salt );
    }
    answerElement.setAttribute( ChaiResponseSet.XML_ATTRIBUTE_CONTENT_FORMAT, formatType.toString() );
    if ( hashCount > 1 )
    {
        answerElement.setAttribute( ChaiResponseSet.XML_ATTRIBUTE_HASH_COUNT, String.valueOf( hashCount ) );
    }
    return answerElement;
}
 
Example 11
/**
 * Returns one of the three notes that can be saved with the desktop.
 *
 * @param nr the number of the notes, either 1, 2 or 3
 * @param note the content of the notes-textfield
 */
public void setDesktopNotes(int nr, String note) {
    // check for valid parameter
    if (nr >= 1 && nr <= 3 && note != null) {
        // first check, whether the note has been modified or not. therefor, retrieve
        // current note-text and compare it to the parameter
        String currentnote = getDesktopNotes(nr);
        // if notes don't equal, go on...
        if (!currentnote.equals(note)) {
            // get all children from deskopNotes, since we need to find the right
            // desktop-element first...
            List<Element> elementList = desktopNotes.getRootElement().getChildren();
            // create an iterartor
            Iterator<Element> it = elementList.iterator();
            // go through all desktop-elements of the desktopNores-file
            while (it.hasNext()) {
                // retrieve element
                Element desk = it.next();
                // get name sttribute
                String att = desk.getAttributeValue("name");
                // check for desktop-name
                if (att != null && att.equals(getCurrentDesktopName())) {
                    // retrieve notes-element
                    Element el = desk.getChild("notes" + String.valueOf(nr));
                    // set note text
                    el.setText(note);
                    // change modify-tag
                    setModified(true);
                }
            }
        }
    }
}
 
Example 12
static void fixHostGenre(BibtexEntry entry, Element mods) {
    String type = entry.getEntryType().toLowerCase(Locale.ROOT);
    if ("incollection".equals(type) || "inproceedings".equals(type) || "inbook".equals(type)) {
        type = type.substring(2);

        Element genre = getHostGenre(mods);
        if (genre != null) {
            genre.setText(type);
        } else {
            MCRFieldTransformer.buildElement("mods:relatedItem[@type='host']/mods:genre", type, mods);
        }
    }
}
 
Example 13
/**
 * This method sets an accelerator key of an related action. To change an accelerator key,
 * provide the action's name and the keystroke-value as string parameters. furthermore, we
 * have to tell the method, to which file the changes should be applied (param what).
 * 
 * Following constants should be used as parameters:<br>
 * MAINKEYS<br>
 * NEWENTRYKEYS<br>
 * DESKTOPKEYS<br>
 * SEARCHRESULTSKEYS<br>
 * 
 * @param what (uses constants, see global field definition at top of source)
 * @param action (the action's name, as string, e.g. "newEntry")
 * @param keystroke (the keystroke, e.g. "ctrl N" (win/linux) or "meta O" (mac)
 */
public void setAccelerator(int what, String action, String keystroke) {
    // create a list of all elements from the xml file
    try {
        List<?> elementList = getDocument(what).getRootElement().getContent();
        // and an iterator for the loop below
        Iterator<?> iterator = elementList.iterator();

        // counter for the return value if a found element attribute matches the parameter
        int cnt = 1;
        // iterate loop
        while (iterator.hasNext()) {
            // retrieve each single element
            Element acckey = (Element) iterator.next();
            // if action-attribute matches the parameter string...
            if (action.equals(acckey.getAttributeValue("action"))) {
                // ...set the new keystroke
                acckey.setText(keystroke);
                // and leave method
                return;
            }
            // else increase counter
            cnt++;
        }
    }
    catch (IllegalStateException e) {
        Constants.zknlogger.log(Level.WARNING,e.getLocalizedMessage());
    }
}
 
Example 14
/**
 * If matches(), adds MODS elements mapped to the matching groups in the pattern.
 * Note that matches() MUST be called first!
 * 
 * @param extent the mods:extent element to add new MODS elements to
 */
void addMODSto(Element extent) {
    for (Entry<String, Integer> mapping : pattern.getMappings()) {
        int group = mapping.getValue();
        String name = mapping.getKey();
        Element mods = new Element(name, MCRConstants.MODS_NAMESPACE);
        String value = matcher.group(group);
        mods.setText(value);
        extent.addContent(mods);
    }
}
 
Example 15
/**
 * Builds a jdom document containing the error parameter.
 * 
 * @param msg the message of the error
 * @param statusCode the http status code
 * @param requestURI the uri of the request
 * @param exceptionType type of the exception
 * @param source source of the error 
 * @param ex exception which is occured
 * 
 * @return jdom document containing all error parameter
 */
public static Document buildErrorPage(String msg, Integer statusCode, String requestURI,
    Class<? extends Throwable> exceptionType, String source, Throwable ex) {
    String rootname = MCRConfiguration2.getString("MCR.Frontend.ErrorPage").orElse("mcr_error");
    Element root = new Element(rootname);
    root.setAttribute("errorServlet", Boolean.TRUE.toString());
    root.setAttribute("space", "preserve", Namespace.XML_NAMESPACE);
    if (msg != null) {
        root.setText(msg);
    }
    if (statusCode != null) {
        root.setAttribute("HttpError", statusCode.toString());
    }
    if (requestURI != null) {
        root.setAttribute("requestURI", requestURI);
    }
    if (exceptionType != null) {
        root.setAttribute("exceptionType", exceptionType.getName());
    }
    if (source != null) {
        root.setAttribute("source", source);
    }
    while (ex != null) {
        Element exception = new Element("exception");
        exception.setAttribute("type", ex.getClass().getName());
        Element trace = new Element("trace");
        Element message = new Element("message");
        trace.setText(MCRException.getStackTraceAsString(ex));
        message.setText(ex.getMessage());
        exception.addContent(message).addContent(trace);
        root.addContent(exception);
        ex = ex.getCause();
    }
    return new Document(root, new DocType(rootname));
}
 
Example 16
@Override
public Element createXML() throws MCRException {
    Element element = super.createXML();
    return element.setText(this.data.stream().map(BigDecimal::toPlainString).collect(Collectors.joining(",")));
}
 
Example 17
public static void setStringValue(Element element, String value)
{
	element.setText(value);
	XMLUtils.removeAttribute(element, XML_WARNING);
	XMLUtils.removeAttribute(element, XML_ERROR);
}
 
Example 18
/**
 * merges content of two elements recursively into element minor following
 * content will be copied: Text, Element, Attribute if conflicts, minor will
 * be overwrite with content of major
 * 
 * @param minor
 * @param major
 */
public static boolean mergeElements(Element minor, Element major) throws Exception
{
	// logger.debug("minor: " + Utils.element2String(minor, false));
	// logger.debug("major: " + Utils.element2String(major, false));
	boolean changed = false;
	if (minor == null)
	{
		minor = major;
		// logger.debug("set minor = " + Utils.element2String(major, false));
		changed = true;
	}
	else if (major != null)
	{
		if (!minor.getText().equals(major.getText()))
		{
			minor.setText(major.getText());
			// logger.debug("minor.setText("+major.getText()+")");
			changed = true;
		}

		for (Attribute a : (List<Attribute>) major.getAttributes())
		{
			Attribute aCopy = (Attribute) Utils.deepCopy(a);
			if (minor.getAttribute(a.getName()) == null || !minor.getAttributeValue(a.getName()).equals(a.getValue()))
			{
				minor.setAttribute(aCopy.detach());
				// logger.debug("minor.setAttribute("+Utils.toString(a)+")");
				changed = true;
			}
		}

		for (Element e : (List<Element>) major.getChildren())
		{
			Element eCopy = (Element) Utils.deepCopy(e);
			List<Element> minorChildren = minor.getChildren(e.getName());
			// logger.debug("minorChildren: " + Utils.toString(minorChildren));
			// logger.debug("e: " + Utils.toString(e));
			Element firstInList = existInList(minorChildren, e);
			if (firstInList == null)
			{
				// logger.debug("minor.addContent: " +
				// Utils.toString(eCopy.detach()));
				minor = minor.addContent(eCopy.detach());
				// logger.debug("minor.addContent("+Utils.element2String(e,
				// false)+")");
				changed = true;
			}
			else
			{
				changed = mergeElements(firstInList, eCopy) || changed;
			}
		}
	}

	return changed;
}
 
Example 19
/**
 * Sets or adds an element with target name and value. The element name and attributes are used as xpath expression
 * to filter for an element. The attributes are used with and operation if present.
 */
public Optional<Element> setElement(String elementName, String elementValue, Map<String, String> attributes) {
    boolean isAttributeDataPresent = attributes != null && !attributes.isEmpty();
    boolean isValuePresent = elementValue != null && !elementValue.isEmpty();

    if (!isValuePresent && !isAttributeDataPresent) {
        return Optional.empty();
    }

    StringBuilder xPath = new StringBuilder("mods:");
    xPath.append(elementName);

    // add attributes to xpath with and operator
    if (isAttributeDataPresent) {

        xPath.append('[');
        Iterator<Map.Entry<String, String>> attributeIterator = attributes.entrySet().iterator();
        while (attributeIterator.hasNext()) {
            Map.Entry<String, String> attribute = attributeIterator.next();
            xPath.append('@').append(attribute.getKey()).append("='").append(attribute.getValue()).append('\'');

            if (attributeIterator.hasNext()) {
                xPath.append(" and ");
            }
        }
        xPath.append(']');
    }
    Element element = getElement(xPath.toString());

    if (element == null) {
        element = addElement(elementName);
        if (isAttributeDataPresent) {
            for (Map.Entry<String, String> entry : attributes.entrySet()) {
                element.setAttribute(entry.getKey(), entry.getValue());
            }
        }
    }

    if (isValuePresent) {
        element.setText(elementValue.trim());
    }

    return Optional.of(element);
}
 
Example 20
/**
 * Creates the epicur lite xml.
 */
public Document toXML() {
    //TODO support multiple url elements

    Element epicurLite = newEpicureElement("epicurlite");
    epicurLite.addNamespaceDeclaration(XSI_NAMESPACE);
    epicurLite.setAttribute("schemaLocation",
        "http://nbn-resolving.org/epicurlite http://nbn-resolving.org/schemas/epicurlite/1.0/epicurlite.xsd",
        XSI_NAMESPACE);
    Document epicurLiteDoc = new Document(epicurLite);

    // authentication information
    if (credentials != null) {
        Element login = newEpicureElement("login");
        Element password = newEpicureElement("password");
        login.setText(credentials.getUserName());
        password.setText(credentials.getPassword());
        epicurLite.addContent(login);
        epicurLite.addContent(password);
    }

    // urn element
    Element identifier = newEpicureElement("identifier");
    Element value = newEpicureElement("value");
    value.setText(urn.getIdentifier());
    epicurLite.addContent(identifier.addContent(value));

    // resource Element
    Element resource = newEpicureElement("resource");
    Element urlElem = newEpicureElement("url");

    urlElem.setText(url.toString());

    Element primary = newEpicureElement("primary");
    primary.setText(String.valueOf(isPrimary));

    Element frontpage = newEpicureElement("frontpage");
    frontpage.setText(String.valueOf(isFrontpage));
    resource.addContent(urlElem);
    resource.addContent(primary);
    resource.addContent(frontpage);

    epicurLite.addContent(resource);

    return epicurLiteDoc;
}