Example usage for org.dom4j DocumentFactory createDocument

List of usage examples for org.dom4j DocumentFactory createDocument

Introduction

In this page you can find the example usage for org.dom4j DocumentFactory createDocument.

Prototype

public Document createDocument() 

Source Link

Usage

From source file:com.openedit.users.filesystem.XmlUserArchive.java

License:Open Source License

public void saveUser(User user) throws UserManagerException {
    if (user.isVirtual()) {
        log.error("Cannot save virtual users: " + user.getUserName());
        return;// w  ww . j  a va  2  s. co m
    }
    DocumentFactory factory = DocumentFactory.getInstance();
    Document doc = factory.createDocument();
    Element userElem = doc.addElement("user");
    userElem.addAttribute("enabled", Boolean.toString(user.isEnabled()));
    if (user.getUserName() == null) {
        int id = getUserIdCounter().incrementCount();
        String newid = String.valueOf(id);
        user.setId(newid);
    }
    Element userNameElem = userElem.addElement("user-name");
    userNameElem.addCDATA(user.getUserName());

    Element passwordElem = userElem.addElement("password");
    //
    if (user.getPassword() != null && !user.getPassword().equals("")) {
        String ps = user.getPassword();
        ps = encrypt(ps);
        // password may have changed we should set it so it's not in plain
        // text anymore.
        user.setPassword(ps);
        passwordElem.addCDATA(ps);
    }
    Element creationDateElem = userElem.addElement("creation-date");
    if (user.getCreationDate() != null) {
        creationDateElem.setText(String.valueOf(user.getCreationDate().getTime()));
    } else {
        creationDateElem.setText(String.valueOf(System.currentTimeMillis()));
    }

    // Tuan add property lastLogined-Time
    Element lastLoginTime = userElem.addElement("lastLogined-Time");
    lastLoginTime.setText(DateStorageUtil.getStorageUtil().formatForStorage(new Date()));

    MapPropertyContainer map = (MapPropertyContainer) user.getPropertyContainer();
    if (map != null) {
        Element propertiesElem = map.createPropertiesElement("properties");
        userElem.add(propertiesElem);
    }
    if (user.getGroups() != null) {
        for (Iterator iter = user.getGroups().iterator(); iter.hasNext();) {
            Group group = (Group) iter.next();
            Element child = userElem.addElement("group");
            child.addAttribute("id", group.getId());
        }
    }
    synchronized (user) {
        // File file = loadUserFile(user.getUserName());
        XmlFile xfile = new XmlFile();
        xfile.setRoot(doc.getRootElement());
        xfile.setPath(getUserDirectory() + "/" + user.getUserName() + ".xml");
        getXmlArchive().saveXml(xfile, null);

        getUserNameToUserMap().put(user.getUserName(), user);
    }
}

From source file:edu.umd.cs.findbugs.SortedBugCollection.java

License:Open Source License

/**
 * Convert the BugCollection into a dom4j Document object.
 *
 * @return the Document representing the BugCollection as a dom4j tree
 *///from ww  w . ja va  2  s .  co m
@Override
public Document toDocument() {
    // if (project == null) throw new NullPointerException("No project");
    assert project != null;

    DocumentFactory docFactory = new DocumentFactory();
    Document document = docFactory.createDocument();
    Dom4JXMLOutput treeBuilder = new Dom4JXMLOutput(document);

    try {
        writeXML(treeBuilder);
    } catch (IOException e) {
        // Can't happen
    }
    return document;
}

From source file:nl.ru.cmbi.vase.parse.VASEXMLParser.java

License:Apache License

public static void write(VASEDataObject data, OutputStream xmlOut) throws IOException {

    DocumentFactory df = DocumentFactory.getInstance();

    Document doc = df.createDocument();

    Element root = doc.addElement("xml");

    if (data.getTitle() != null) {

        Element title = root.addElement("title");
        title.setText(data.getTitle());/*from   www.  j  av  a  2 s  . co  m*/
    }

    Element fasta = root.addElement("fasta");
    ByteArrayOutputStream fastaStream = new ByteArrayOutputStream();
    FastaParser.toFasta(data.getAlignment().getMap(), fastaStream);

    fasta.add(df.createCDATA(new String(fastaStream.toByteArray(), StandardCharsets.UTF_8)));

    Element pdb = root.addElement("pdb");
    pdb.addAttribute("pdbid", data.getPdbID());

    table2xml(data.getTable(), root);

    if (data.getPlots().size() > 0) {
        Element plots = root.addElement("plots");
        for (PlotDescription pd : data.getPlots()) {

            Element plot = plots.addElement("plot");
            plot.addElement("x").setText(pd.getXAxisColumnID());
            plot.addElement("y").setText(pd.getYAxisColumnID());
            plot.addAttribute("title", pd.getPlotTitle());
        }
    }

    XMLWriter writer = new XMLWriter(xmlOut);
    writer.write(doc);
    writer.close();
}

From source file:nl.tue.gale.common.XPPEntityReader.java

License:Open Source License

protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = getDocumentFactory();
    Document document = df.createDocument();
    Element parent = null;/*from w  w  w  .j a  va 2  s.c o m*/
    XmlPullParser pp = getXPPParser();
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false);
    defineEntities(pp);

    while (true) {
        int type = pp.nextToken();

        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");

            if (loc >= 0) {
                String target = text.substring(0, loc);
                String txt = text.substring(loc + 1);
                document.addProcessingInstruction(target, txt);
            } else {
                document.addProcessingInstruction(text, "");
            }

            break;
        }

        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }

            break;
        }

        case XmlPullParser.CDSECT: {
            if (parent != null) {
                parent.addCDATA(pp.getText());
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        case XmlPullParser.ENTITY_REF:
            if (parent != null) {
                if (pp.getName().equals("gt")) {
                    parent.addText(">");
                } else if (pp.getName().equals("lt")) {
                    parent.addText("<");
                } else if (pp.getName().equals("amp")) {
                    parent.addText("&");
                } else if (pp.getName().equals("quot")) {
                    parent.addText("\"");
                } else
                    parent.addEntity(pp.getName(), "&" + pp.getName() + ";");
            }
            break;

        case XmlPullParser.END_DOCUMENT:
            return document;

        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = df.createElement(qname);
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());

            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }

            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }

            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }

            parent = newElement;

            break;
        }

        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }

            break;
        }

        case XmlPullParser.TEXT: {
            String text = pp.getText();

            if (parent != null) {
                parent.addText(text);
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        default:
            break;
        }
    }
}

From source file:no.met.jtimeseries.service.ServiceDescriptionGenerator.java

License:Open Source License

/**
 * Create a description of the web service offered by a class in XML. The
 * documentation is created by looking at the web service annotations.
 *
 * @param c//  w  ww.  j  av a  2 s. c  om
 *            The class to generate documentation for.
 * @return A XML document object.
 */
public static Document getXMLServiceDescription(Class<? extends Object> c) {

    List<Method> serviceMethods = getServiceMethods(c);

    DocumentFactory df = new DocumentFactory();
    Document xmlDoc = df.createDocument();

    Element rootElement = df.createElement("services");
    xmlDoc.add(rootElement);
    for (Method m : serviceMethods) {

        Element service = rootElement.addElement("service");
        MethodInfo mi = getMethodInfo(m);
        service.addAttribute("path", mi.path);

        if (mi.produces != null) {
            service.addAttribute("returmMimeType", StringUtils.join(mi.produces, ','));
        }

        if (mi.description != null) {
            service.addAttribute("description", mi.description);
        }

        List<ParameterInfo> params = getParameters(m);
        for (ParameterInfo pi : params) {
            Element param = service.addElement("parameter");
            param.addAttribute("name", pi.name);
            if (pi.defaultValue != null) {
                param.addAttribute("defaultValue", pi.defaultValue);
            }
        }
    }

    return xmlDoc;
}

From source file:org.foxbpm.bpmn.converter.BpmnXMLConverter.java

License:Apache License

/**
 * bpmnModel??documnet/* ww w. ja  va  2  s  . c o  m*/
 * 
 * @param model
 *            bpmn
 */
public Document convertToXML(BpmnModel model) {

    if (null == model) {
        throw new BpmnConverterException("?XML?!");
    }

    DocumentFactory factory = DocumentFactory.getInstance();
    Document doc = factory.createDocument();
    Element element = factory.createElement(
            BpmnXMLConstants.BPMN2_PREFIX + ':' + BpmnXMLConstants.ELEMENT_DEFINITIONS,
            BpmnXMLConstants.BPMN2_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.XSI_PREFIX, BpmnXMLConstants.XSI_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.DC_PREFIX, BpmnXMLConstants.DC_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.DI_PREFIX, BpmnXMLConstants.DI_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.BPMNDI_PREFIX, BpmnXMLConstants.BPMNDI_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.FOXBPM_PREFIX, BpmnXMLConstants.FOXBPM_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.XSD_PREFIX, BpmnXMLConstants.XSD_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.EMPTY_STRING, BpmnXMLConstants.XMLNS_NAMESPACE);
    // 
    element.addAttribute(BpmnXMLConstants.TARGET_NAMESPACE_ATTRIBUTE, BpmnXMLConstants.XMLNS_NAMESPACE);
    element.addAttribute(BpmnXMLConstants.ATTRIBUTE_ID, "Definitions_1");
    doc.add(element);
    // ??
    try {
        for (Iterator<Process> iterator = model.getProcesses().iterator(); iterator.hasNext();) {
            ProcessExport.writeProcess(iterator.next(), element);
        }
        // ????
        BPMNDIExport.writeBPMNDI(model, element);
    } catch (Exception e) {
        LOGGER.error("?XML???" + model.getProcesses().get(0).getName(), e);
        if (e instanceof BpmnConverterException) {
            throw (BpmnConverterException) e;
        } else {
            throw new BpmnConverterException(
                    "?XML???" + model.getProcesses().get(0).getName(), e);
        }
    }
    return doc;
}

From source file:org.olat.core.gui.control.generic.textmarker.TextMarkerManagerImpl.java

License:Apache License

/**
 * @see org.olat.core.gui.control.generic.textmarker.TextMarkerManager#saveToFile(org.olat.core.util.vfs.VFSLeaf, java.util.List)
 */// ww  w  .j av  a  2 s .c  o m
@Override
public void saveToFile(VFSLeaf textMarkerFile, List textMarkerList) {
    DocumentFactory df = DocumentFactory.getInstance();
    Document doc = df.createDocument();
    // create root element with version information
    Element root = df.createElement(XML_ROOT_ELEMENT);
    root.addAttribute(XML_VERSION_ATTRIBUTE, String.valueOf(VERSION));
    doc.setRootElement(root);
    // add TextMarker elements
    Iterator iter = textMarkerList.iterator();
    while (iter.hasNext()) {
        TextMarker textMarker = (TextMarker) iter.next();
        textMarker.addToElement(root);
    }
    OutputStream stream = textMarkerFile.getOutputStream(false);
    try {
        XMLWriter writer = new XMLWriter(stream);
        writer.write(doc);
        writer.close();
        stream.close();
    } catch (UnsupportedEncodingException e) {
        Tracing.logError("Error while saving text marker file", e, TextMarkerManagerImpl.class);
    } catch (IOException e) {
        Tracing.logError("Error while saving text marker file", e, TextMarkerManagerImpl.class);
    }
}

From source file:org.olat.ims.qti.qpool.QTIExportProcessor.java

License:Apache License

private Element createSectionBasedAssessment(String title) {
    DocumentFactory df = DocumentFactory.getInstance();
    Document doc = df.createDocument();
    doc.addDocType(QTIConstants.XML_DOCUMENT_ROOT, null, QTIConstants.XML_DOCUMENT_DTD);

    /*/*from  w ww . j  a v  a  2 s.co m*/
    <questestinterop>
      <assessment ident="frentix_9_87230240084930" title="SR Test">
     */
    Element questestinterop = doc.addElement(QTIConstants.XML_DOCUMENT_ROOT);
    Element assessment = questestinterop.addElement("assessment");
    assessment.addAttribute("ident", CodeHelper.getGlobalForeverUniqueID());
    assessment.addAttribute("title", title);
    //metadata
    /*
    <qtimetadata>
       <qtimetadatafield>
      <fieldlabel>qmd_assessmenttype</fieldlabel>
      <fieldentry>Assessment</fieldentry>
    </qtimetadatafield>
    </qtimetadata>
    */
    Element qtimetadata = assessment.addElement("qtimetadata");
    addMetadataField("qmd_assessmenttype", "Assessment", qtimetadata);
    //section
    /*
    <section ident="frentix_9_87230240084931" title="Section">
     <selection_ordering>
       <selection/>
       <order order_type="Sequential"/>
     </selection_ordering>
    */
    Element section = assessment.addElement("section");
    section.addAttribute("ident", CodeHelper.getGlobalForeverUniqueID());
    section.addAttribute("title", "Section");
    Element selectionOrdering = section.addElement("selection_ordering");
    selectionOrdering.addElement("selection");
    Element order = selectionOrdering.addElement("order");
    order.addAttribute("order_type", "Sequential");
    return section;
}

From source file:org.olat.ims.qti.qpool.QTIImportProcessor.java

License:Apache License

protected void processAssessmentFiles(QuestionItemImpl item, ItemInfos itemInfos) {
    //a package with an item
    String dir = item.getDirectory();
    String rootFilename = item.getRootFilename();
    VFSContainer container = qpoolFileStorage.getContainer(dir);
    VFSLeaf endFile = container.createChildLeaf(rootFilename);

    //embed in <questestinterop>
    DocumentFactory df = DocumentFactory.getInstance();
    Document itemDoc = df.createDocument();
    Element questestinteropEl = df.createElement(QTIDocument.DOCUMENT_ROOT);
    itemDoc.setRootElement(questestinteropEl);
    Element deepClone = (Element) itemInfos.getItemEl().clone();
    questestinteropEl.add(deepClone);/*from   www  . j a v  a 2  s  .com*/

    //write
    try {
        OutputStream os = endFile.getOutputStream(false);
        ;
        XMLWriter xw = new XMLWriter(os, new OutputFormat("  ", true));
        xw.write(itemDoc.getRootElement());
        xw.close();
        os.close();
    } catch (IOException e) {
        log.error("", e);
    }

    //there perhaps some other materials
    if (importedFilename.toLowerCase().endsWith(".zip")) {
        processAssessmentMaterials(deepClone, container);
    }
}

From source file:org.olat.ims.qti.render.ResultsBuilder.java

License:Apache License

/**
 * Method getResDoc.//from ww w  . ja  v  a  2s.  c  o m
 * 
 * @param ai The assessment instance
 * @param locale The users locale
 * @param identity
 * @return Document The XML document
 */
public Document getResDoc(final AssessmentInstance ai, final Locale locale, final Identity identity) {
    final AssessmentContext ac = ai.getAssessmentContext();
    final DocumentFactory df = DocumentFactory.getInstance();
    final Document res_doc = df.createDocument();
    final Element root = df.createElement("qti_result_report");
    res_doc.setRootElement(root);
    final Element result = root.addElement("result");
    final Element extension_result = result.addElement("extension_result");

    // add items (not qti standard, but nice to display original questions ->
    // put it into extensions)
    // extension_result.
    final int sectioncnt = ac.getSectionContextCount();
    for (int i = 0; i < sectioncnt; i++) {
        final SectionContext sc = ac.getSectionContext(i);
        final int itemcnt = sc.getItemContextCount();
        for (int j = 0; j < itemcnt; j++) {
            final ItemContext it = sc.getItemContext(j);
            final Element el_item = it.getEl_item();
            extension_result.add(el_item);
        }
    }

    // add ims cp id for any media references
    addStaticsPath(extension_result, ai);

    // add assessment_result

    // Add User information
    final Element context = result.addElement("context");
    final User user = identity.getUser();
    final String name = user.getProperty(UserConstants.LASTNAME, locale) + " "
            + user.getProperty(UserConstants.FIRSTNAME, locale) + " (" + identity.getName() + ")";
    String instId = user.getProperty(UserConstants.INSTITUTIONALUSERIDENTIFIER, locale);
    final String instName = user.getProperty(UserConstants.INSTITUTIONALNAME, locale);

    if (instId == null) {
        instId = "N/A";
    }
    context.addElement("name").addText(name);

    String institution;
    if (instName == null) {
        institution = "N/A";
    } else {
        institution = instName;
    }
    if (institution == null) {
        institution = "N/A";
    }

    // Add institutional identifier (e.g. Matrikelnummer)
    final Element generic_identifier = context.addElement("generic_identifier");
    generic_identifier.addElement("type_label").addText(institution);
    generic_identifier.addElement("identifier_string").addText(instId);

    // Add start and stop date formatted as datetime
    final Element beginDate = context.addElement("date");
    beginDate.addElement("type_label").addText("Start");
    beginDate.addElement("datetime").addText(Formatter.formatDatetime(new Date(ac.getTimeOfStart())));
    final Element stopDate = context.addElement("date");
    stopDate.addElement("type_label").addText("Stop");
    stopDate.addElement("datetime").addText(Formatter.formatDatetime(new Date(ac.getTimeOfStop())));

    final Element ares = result.addElement("assessment_result");
    ares.addAttribute("ident_ref", ac.getIdent());
    if (ac.getTitle() != null) {
        ares.addAttribute("asi_title", ac.getTitle());
    }

    // process assessment score
    final Element a_score = ares.addElement("outcomes").addElement("score");
    a_score.addAttribute("varname", "SCORE");
    String strVal = StringHelper.formatFloat(ac.getScore(), 2);
    a_score.addElement("score_value").addText(strVal);

    strVal = ac.getMaxScore() == -1.0f ? "N/A" : StringHelper.formatFloat(ac.getMaxScore(), 2);
    a_score.addElement("score_max").addText(strVal);

    strVal = ac.getCutvalue() == -1.0f ? "N/A" : StringHelper.formatFloat(ac.getCutvalue(), 2);
    a_score.addElement("score_cut").addText(strVal);

    addElementText(ares, "duration", QTIHelper.getISODuration(ac.getDuration()));
    addElementText(ares, "num_sections", "" + ac.getSectionContextCount());
    addElementText(ares, "num_sections_presented", "0");
    addElementText(ares, "num_items", "" + ac.getItemContextCount());
    addElementText(ares, "num_items_presented", "" + ac.getItemsPresentedCount());
    addElementText(ares, "num_items_attempted", "" + ac.getItemsAttemptedCount());

    // add section_result
    final int secnt = ac.getSectionContextCount();
    for (int i = 0; i < secnt; i++) {
        final SectionContext secc = ac.getSectionContext(i);
        final Element secres = ares.addElement("section_result");
        secres.addAttribute("ident_ref", secc.getIdent());
        if (secc.getTitle() != null) {
            secres.addAttribute("asi_title", secc.getTitle());
        }
        addElementText(secres, "duration", QTIHelper.getISODuration(secc.getDuration()));
        addElementText(secres, "num_items", "" + secc.getItemContextCount());
        addElementText(secres, "num_items_presented", "" + secc.getItemsPresentedCount());
        addElementText(secres, "num_items_attempted", "" + secc.getItemsAttemptedCount());

        // process section score
        final Element sec_score = secres.addElement("outcomes").addElement("score");
        sec_score.addAttribute("varname", "SCORE");
        strVal = secc.getScore() == -1.0f ? "N/A" : "" + StringHelper.formatFloat(secc.getScore(), 2);
        sec_score.addElement("score_value").addText(strVal);
        strVal = secc.getMaxScore() == -1.0f ? "N/A" : "" + StringHelper.formatFloat(secc.getMaxScore(), 2);
        sec_score.addElement("score_max").addText(strVal);
        strVal = secc.getCutValue() == -1 ? "N/A" : "" + secc.getCutValue();
        sec_score.addElement("score_cut").addText(strVal);

        // iterate over all items in this section context
        final List itemsc = secc.getSectionItemContexts();
        for (final Iterator it_it = itemsc.iterator(); it_it.hasNext();) {
            final ItemContext itemc = (ItemContext) it_it.next();
            final Element itres = secres.addElement("item_result");
            itres.addAttribute("ident_ref", itemc.getIdent());
            itres.addAttribute("asi_title", itemc.getEl_item().attributeValue("title"));
            final Element it_duration = itres.addElement("duration");
            it_duration.addText(QTIHelper.getISODuration(itemc.getTimeSpent()));

            // process item score
            final DecimalVariable scoreVar = (DecimalVariable) (itemc.getVariables().getSCOREVariable());
            final Element it_score = itres.addElement("outcomes").addElement("score");
            it_score.addAttribute("varname", "SCORE");
            it_score.addElement("score_value")
                    .addText(StringHelper.formatFloat(scoreVar.getTruncatedValue(), 2));
            strVal = scoreVar.hasMinValue() ? "" + scoreVar.getMinValue() : "0.0";
            it_score.addElement("score_min").addText(strVal);
            strVal = scoreVar.hasMaxValue() ? "" + scoreVar.getMaxValue() : "N/A";
            it_score.addElement("score_max").addText(strVal);
            strVal = scoreVar.hasCutValue() ? "" + scoreVar.getCutValue() : "N/A";
            it_score.addElement("score_cut").addText(strVal);

            final Element el_item = itemc.getEl_item();
            final Map res_responsehash = new HashMap(3);

            // iterate over all responses of this item
            final List resps = el_item.selectNodes(
                    ".//response_lid|.//response_xy|.//response_str|.//response_num|.//response_grp");
            for (final Iterator it_resp = resps.iterator(); it_resp.hasNext();) {
                final Element resp = (Element) it_resp.next();
                final String ident = resp.attributeValue("ident");
                final String rcardinality = resp.attributeValue("rcardinality");
                final String rtiming = resp.attributeValue("rtiming");

                // add new response
                final Element res_response = itres.addElement("response");
                res_response.addAttribute("ident_ref", ident);
                res_responsehash.put(ident, res_response); // enable lookup of
                // @identref of <response>
                // (needed with <varequal>
                // elements

                // add new response_form
                // <response_lid ident="MR01" rcardinality="Multiple" rtiming="No">
                final Element res_responseform = res_response.addElement("response_form");
                res_responseform.addAttribute("cardinality", rcardinality);
                res_responseform.addAttribute("timing", rtiming);
                final String respName = resp.getName();
                final String type = respName.substring(respName.indexOf("_") + 1);
                res_responseform.addAttribute("response_type", type);

                // add user answer
                final ItemInput itemInp = itemc.getItemInput();
                final Translator trans = Util.createPackageTranslator(QTIModule.class, locale);
                if (itemInp == null) { // user did not answer this question at all
                    res_response.addElement("response_value").addText(trans.translate("ResBuilder.NoAnswer"));
                } else {
                    final List userAnswer = itemInp.getAsList(ident);
                    if (userAnswer == null) { // user did not answer this question at
                        // all
                        res_response.addElement("response_value")
                                .addText(trans.translate("ResBuilder.NoAnswer"));
                    } else { // the user chose at least one option of an answer (did not
                             // simply click send)
                        for (final Iterator it_ans = userAnswer.iterator(); it_ans.hasNext();) {
                            res_response.addElement("response_value").addText((String) it_ans.next());
                        }
                    }
                }

            }

            /*
             * The simple element correct_response can only list correct elements, that is, no "or" or "and" elements may be in the conditionvar. Pragmatic solution:
             * if condition has ors or ands, then put whole conditionvar into <extension_response> (proprietary), and for easier cases (just "varequal" "not"
             * elements) use correct_response.
             */

            final Map corr_answers = new HashMap(); // keys: respIdents, values: HashSet
            // of correct answers for this
            // respIdent
            final List respconds = el_item.selectNodes(".//respcondition");
            for (final Iterator it_respc = respconds.iterator(); it_respc.hasNext();) {
                final Element el_respc = (Element) it_respc.next();

                // check for add/set in setvar elements (check for single instance
                // only -> spec allows for multiple instances)
                final Element el_setvar = (Element) el_respc.selectSingleNode(".//setvar");
                if (el_setvar == null) {
                    continue;
                }
                if (el_setvar.attributeValue("action").equals("Add")
                        || el_setvar.attributeValue("action").equals("Set")) {
                    // This resrocessing gives points -> assume correct answer
                    float numPoints = 0;
                    try {
                        numPoints = Float.parseFloat(el_setvar.getTextTrim());
                    } catch (final NumberFormatException nfe) {
                        //
                    }
                    if (numPoints <= 0) {
                        continue;
                    }
                    Element conditionvar = (Element) el_respc.selectSingleNode(".//conditionvar");
                    // there is an evaluation defined (a "resprocessing" element exists)
                    // if (xpath(count(.//varequal) + count(.//not) = count(.//*)) is
                    // true, then there are only "not" and "varequal" elements
                    final XPath xCanHandle = DocumentHelper
                            .createXPath("count(.//varequal) + count(.//not) = count(.//*)");
                    boolean canHandle = xCanHandle.matches(conditionvar);
                    if (!canHandle) { // maybe we have <condvar> <and> <...>, try again
                        final Element el_and = (Element) conditionvar.selectSingleNode("and");
                        if (el_and != null) {
                            canHandle = xCanHandle.matches(el_and);
                            if (canHandle) { // simultate the el_and to be the conditionvar
                                conditionvar = el_and;
                            }
                        } else { // and finally, maybe we have an <or> element ..
                            final Element el_or = (Element) conditionvar.selectSingleNode("or");
                            if (el_or != null) {
                                canHandle = xCanHandle.matches(el_or);
                                if (canHandle) { // simultate the el_and to be the conditionvar
                                    conditionvar = el_or;
                                }
                            }
                        }
                    }

                    if (!canHandle) {
                        // qti res 1.2.1 can't handle it
                        final Element condcopy = conditionvar.createCopy();
                        itres.addElement("extension_item_result").add(condcopy);
                    } else {
                        /*
                         * easy case: get all varequal directly under the conditionvar element and assume the "not" elements do not contain "not" elements again...
                         * <!ELEMENT response (qti_comment? , response_form? , num_attempts? , response_value* , extension_response?)> <!ELEMENT response_form
                         * (correct_response* , extension_responseform?)> <!ELEMENT correct_response (#PCDATA)>
                         */
                        final List vareqs = conditionvar.selectNodes("./varequal");
                        for (final Iterator it_vareq = vareqs.iterator(); it_vareq.hasNext();) {
                            /*
                             * get the identifier of the response, so that we can attach the <correct_response> to the right <response> element quote: ims qti asi xml
                             * binding :3.6.23.1 <varequal> Element: respident (required). The identifier of the corresponding <response_lid>, <response_xy>, etc.
                             * element (this was assigned using its ident attribute).
                             */
                            final Element vareq = (Element) it_vareq.next();
                            final String respIdent = vareq.attributeValue("respident");
                            Set respIdent_corr_answers = (Set) corr_answers.get(respIdent);
                            if (respIdent_corr_answers == null) {
                                respIdent_corr_answers = new HashSet(3);
                            }
                            respIdent_corr_answers.add(vareq.getText());
                            corr_answers.put(respIdent, respIdent_corr_answers);
                        } // for varequal
                    } // else varequal
                } // add/set setvar
            } // for resprocessing
            final Set resp_ids = corr_answers.keySet();
            for (final Iterator idents = resp_ids.iterator(); idents.hasNext();) {
                final String respIdent = (String) idents.next();
                final Set respIdent_corr_answers = (Set) corr_answers.get(respIdent);
                final Element res_response = (Element) res_responsehash.get(respIdent);
                final Element res_respform = res_response.element("response_form");
                for (final Iterator iter = respIdent_corr_answers.iterator(); iter.hasNext();) {
                    final String answer = (String) iter.next();
                    res_respform.addElement("correct_response").addText(answer);
                }
            }
        } // for response_xy
    }
    return res_doc;
}