Java Code Examples for org.dom4j.Element#addElement()

The following examples show how to use org.dom4j.Element#addElement() . 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
Source File: ResourceUtil.java    From das with Apache License 2.0 6 votes vote down vote up
public boolean initializeDasSetXml() throws Exception {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(DATA_SET_ROOT).addAttribute("name", DAS_SET_APPID);
    root.addElement("databaseSets").addElement("databaseSet")
            .addAttribute("name", DATA_SET_BASE).addAttribute("provider", "mysqlProvider")
            .addElement("add")
            .addAttribute("name", DATA_BASE)
            .addAttribute("connectionString", DATA_BASE)
            .addAttribute("databaseType", "Master")
            .addAttribute("sharding", "1");
    Element connectionLocator =  root.addElement("ConnectionLocator");
    connectionLocator.addElement("locator").addText("com.ppdai.das.core.DefaultConnectionLocator");
    connectionLocator.addElement("settings").addElement("dataSourceConfigureProvider").addText("com.ppdai.das.console.config.init.ConsoleDataSourceConfigureProvider");
    try (FileWriter fileWriter = new FileWriter(getDasXmlPath())) {
        XMLWriter writer = new XMLWriter(fileWriter);
        writer.write(document);
        writer.close();
    }
    return true;
}
 
Example 2
Source File: RemoteArticleService.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
private Element createArticleElement(Element channelElement, 
		Object articleId, String title, String author, Date issueDate, String summary, 
		int hitCount, int commentNum, String htmlRef) {
    
    Element itemElement = channelElement.addElement("item");
    itemElement.addElement("id").setText(EasyUtils.obj2String(articleId));
    itemElement.addElement("title").setText(EasyUtils.obj2String(title));
    itemElement.addElement("author").setText(EasyUtils.obj2String(author));
    itemElement.addElement("issueDate").setText(DateUtil.format(issueDate));
    itemElement.addElement("summary").setText(EasyUtils.obj2String(summary));
    itemElement.addElement("hitCount").setText(EasyUtils.obj2String(hitCount));
    itemElement.addElement("commentNum").setText(EasyUtils.obj2String(commentNum));
    itemElement.addElement("htmlRef").setText(EasyUtils.obj2String(htmlRef));
    
    return itemElement;
}
 
Example 3
Source File: ChoiceQuestion.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Build resprocessing for olat response feedbacks (uses naming conventions: respcondition:title is set to _olat_resp_feedback to signal a feedback that it belongs
 * directly to the response with the same response ident as the current feedback)
 * 
 * @param resprocessingXML
 */
private void buildRespconditionOlatFeedback(final Element resprocessingXML) {
    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final Element respcondition = resprocessingXML.addElement("respcondition");
        respcondition.addAttribute("title", "_olat_resp_feedback");
        respcondition.addAttribute("continue", "Yes");

        final Element conditionvar = respcondition.addElement("conditionvar");

        final ChoiceResponse tmpChoice = (ChoiceResponse) i.next();
        final Element varequal = conditionvar.addElement("varequal");
        varequal.addAttribute("respident", getIdent());
        varequal.addAttribute("case", "Yes");
        varequal.addText(tmpChoice.getIdent());
        QTIEditHelperEBL.addFeedbackOlatResp(respcondition, tmpChoice.getIdent());
    }
}
 
Example 4
Source File: StudentSectioningXMLSaver.java    From cpsolver with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Save given config
 * @param configEl config element to be populated
 * @param config config to be saved
 */
protected void saveConfig(Element configEl, Config config) {
    configEl.addAttribute("id", getId("config", config.getId()));
    if (config.getLimit() >= 0)
        configEl.addAttribute("limit", String.valueOf(config.getLimit()));
    if (iShowNames)
        configEl.addAttribute("name", config.getName());
    for (Subpart subpart : config.getSubparts()) {
        Element subpartEl = configEl.addElement("subpart");
        saveSubpart(subpartEl, subpart);
    }
    if (config.getInstructionalMethodId() != null) {
        Element imEl = configEl.addElement("instructional-method");
        imEl.addAttribute("id", getId("instructional-method", config.getInstructionalMethodId()));
        if (iShowNames && config.getInstructionalMethodName() != null)
            imEl.addAttribute("name", config.getInstructionalMethodName());
        if (iShowNames && config.getInstructionalMethodReference() != null)
            imEl.addAttribute("reference", config.getInstructionalMethodReference());
    }
}
 
Example 5
Source File: AdHocCommand.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the allowed actions to follow from the current stage. Possible actions are:
 * {@code prev}, {@code next} and {@code complete}.
 *
 * @param data the gathered data through the command stages or {@code null} if the
 *        command does not have stages or the requester is requesting the execution for the
 *        first time.
 * @param command the command element to be sent to the command requester.
 */
protected void addStageActions(SessionData data, Element command) {
    // Add allowed actions to the response
    Element actions = command.addElement("actions");
    List<Action> validActions = getActions(data);
    for (AdHocCommand.Action action : validActions) {
        actions.addElement(action.name());
    }
    Action executeAction = getExecuteAction(data);
    // Add default execute action to the response
    actions.addAttribute("execute", executeAction.name());

    // Store the allowed actions that the user can follow from this stage
    data.setAllowedActions(validActions);
    // Store the default execute action to follow if the user does not specify an
    // action in his command
    data.setExecuteAction(executeAction);
}
 
Example 6
Source File: PersistenceXmlHelper.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void writeForDdlInternalProperty(Element properties) throws Exception {
	Element property = properties.addElement("property");
	property.addAttribute("name", "javax.persistence.jdbc.driver");
	property.addAttribute("value", SlicePropertiesBuilder.driver_h2);
	property = properties.addElement("property");
	property.addAttribute("name", "javax.persistence.jdbc.url");
	Node node = Config.currentNode();
	String url = "jdbc:h2:tcp://" + Config.node() + ":" + node.getData().getTcpPort() + "/X;JMX="
			+ (node.getData().getJmxEnable() ? "TRUE" : "FALSE") + ";CACHE_SIZE="
			+ (node.getData().getCacheSize() * 1024);
	property.addAttribute("value", url);
	property = properties.addElement("property");
	property.addAttribute("name", "javax.persistence.jdbc.user");
	property.addAttribute("value", "sa");
	property = properties.addElement("property");
	property.addAttribute("name", "javax.persistence.jdbc.password");
	property.addAttribute("value", Config.token().getPassword());
	property = properties.addElement("property");
	property.addAttribute("name", "openjpa.DynamicEnhancementAgent");
	property.addAttribute("value", "false");
}
 
Example 7
Source File: XmlMapperTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * 使用Dom4j生成测试用的XML文档字符串.
 */
private static String generateXmlByDom4j() {
	Document document = DocumentHelper.createDocument();

	Element root = document.addElement("user").addAttribute("id", "1");

	root.addElement("name").setText("calvin");

	// List<String>
	Element interests = root.addElement("interests");
	interests.addElement("interest").addText("movie");
	interests.addElement("interest").addText("sports");

	return document.asXML();
}
 
Example 8
Source File: SignExtension.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void marshal(Element element) {
	element.addElement("prefix-type").addText(prefixType.name());
	Element locationElement = element.addElement("location");
	locationElement.addElement("world").addText(location.getWorld().getName());
	locationElement.addElement("x").addText(String.valueOf(location.getBlockX()));
	locationElement.addElement("y").addText(String.valueOf(location.getBlockY()));
	locationElement.addElement("z").addText(String.valueOf(location.getBlockZ()));
}
 
Example 9
Source File: ExtensionLeaderboardPodium.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void marshal(Element element) {
	element.addElement("name").addText(name);
	
	Element locElement = element.addElement("base-location");
	locElement.addElement("world").setText(String.valueOf(baseLocation.getWorld().getName()));
	locElement.addElement("x").setText(String.valueOf(baseLocation.getBlockX()));
	locElement.addElement("y").setText(String.valueOf(baseLocation.getBlockY()));
	locElement.addElement("z").setText(String.valueOf(baseLocation.getBlockZ()));
	
	element.addElement("direction").addText(direction.name());
	element.addElement("size").addText(size.name());
}
 
Example 10
Source File: Feature.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public static void createFeatureElement3(Element rootElement,
		List<Feature> features) {
	for(Feature feature : features) {
		Element featureElement = rootElement.addElement("feature");
		featureElement.addAttribute("name", feature.getName());
		if(feature.getParams().size()>0){
			Element paramElement = featureElement.addElement("param");
			paramElement.addAttribute(feature.getParams().get(0).getValue(),feature.getParams().get(1).getValue());
		}
	}
}
 
Example 11
Source File: XMLUtil.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 设置或添加子元素
 * @param element
 * @param childName
 * @param childValue
 */
public static Element setElementChild(Element element, String childName, String childValue) {
    Element child = element.element(childName);
    if (child != null) {
        child.setText(childValue);
    } else {
        child = element.addElement(childName, childValue);
    }
    return child;
}
 
Example 12
Source File: CourseOfferingExport.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected void exportTimeLocation(Element classElement, Assignment assignment, Session session) {
    TimeLocation time = assignment.getTimeLocation();
    if (time!=null) {
        Element timeElement = classElement.addElement("time");
        timeElement.addAttribute("days", dayCode2days(time.getDayCode()));
        timeElement.addAttribute("startTime", startSlot2startTime(time.getStartSlot()));
        timeElement.addAttribute("endTime", timeLocation2endTime(time));
        DatePattern dp = assignment.getDatePattern();
        if (dp != null && (!dp.isDefault() || ApplicationProperty.DataExchangeIncludeDefaultDatePattern.isTrue()))
        	timeElement.addAttribute("datePattern", dp.getName());
        if (assignment.getTimePattern() != null)
        	timeElement.addAttribute("timePattern", assignment.getTimePattern().getName());
    }
}
 
Example 13
Source File: ExportPreferences.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void exportSubpartStructure(Element parent, SchedulingSubpart s) {
	Element el = parent.addElement("schedulingSubpart");
	el.addAttribute("uniqueId",s.getUniqueId().toString());
	el.addAttribute("itype",s.getItypeDesc());
	el.addAttribute("suffix",s.getSchedulingSubpartSuffix());
	el.addAttribute("minutesPerWk",s.getMinutesPerWk().toString());
	TreeSet subparts = new TreeSet(subpartCmp);
	subparts.addAll(s.getChildSubparts());
	for (Iterator i=subparts.iterator();i.hasNext();) {
		exportSubpartStructure(el, (SchedulingSubpart)s);
	}
	TreeSet classes = new TreeSet(classCmp);
	classes.addAll(s.getClasses());
	for (Iterator i=classes.iterator();i.hasNext();) {
		Class_ c = (Class_)i.next();
		Element x = el.addElement("class");
		x.addAttribute("uniqueId", c.getUniqueId().toString());
		if (c.getParentClass()!=null)
			x.addAttribute("parent", c.getParentClass().getUniqueId().toString());
		x.addAttribute("expectedCapacity", c.getExpectedCapacity().toString());
		x.addAttribute("maxExpectedCapacity", c.getMaxExpectedCapacity().toString());
		x.addAttribute("roomRatio", c.getRoomRatio().toString());
		x.addAttribute("nbrRooms", c.getNbrRooms().toString());
		x.addAttribute("manager", c.getManagingDept().getDeptCode());
		x.addAttribute("sectionNumber", String.valueOf(c.getSectionNumber()));
	}
}
 
Example 14
Source File: DOM4JUtil.java    From TAC with MIT License 5 votes vote down vote up
public static void addLogIdParameter(Document document, String LogId){

        // 通过document对象获取根节点
        Element suiteRoot = document.getRootElement();
        Element parameterNode=suiteRoot.addElement("parameter");
        parameterNode.addAttribute("name","logId");
        parameterNode.addAttribute("value",LogId);

    }
 
Example 15
Source File: ScriptTaskXMLConverter.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@Override
public void convertModelToXML(Element element, BaseElement baseElement) {
	
	ScriptTask scriptTask = (ScriptTask) baseElement;
	if (null != scriptTask.getScript()) {
		element.addAttribute(BpmnXMLConstants.FOXBPM_PREFIX + ':' + BpmnXMLConstants.ATTRIBUTE_SCRIPTNAME, BpmnXMLUtil.interceptStr(scriptTask.getScript()));
		Element childElem = element.addElement(BpmnXMLConstants.BPMN2_PREFIX + ':'
		        + BpmnXMLConstants.ELEMENT_SCRIPT);
		childElem.setText(scriptTask.getScript());
	}
	if (null != scriptTask.getScriptFormat()) {
		element.addAttribute(BpmnXMLConstants.ATTRIBUTE_SCRIPTFORMAT, scriptTask.getScriptFormat());
	}
	super.convertModelToXML(element, baseElement);
}
 
Example 16
Source File: ChoiceQuestion.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Build resprocessing for single choice item. Set score to correct value and use mastery feedback
 * 
 * @param resprocessingXML
 */
private void buildRespconditionSC_mastery(final Element resprocessingXML) {
    final Element respcondition_correct = resprocessingXML.addElement("respcondition");
    respcondition_correct.addAttribute("title", "Mastery");
    respcondition_correct.addAttribute("continue", "Yes");

    final Element conditionvar = respcondition_correct.addElement("conditionvar");
    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        // fetch correct answer (there should be a single instance)
        final ChoiceResponse tmpChoice = (ChoiceResponse) i.next();
        if (!tmpChoice.isCorrect()) {
            continue;
        }

        // found correct answer
        final Element varequal = conditionvar.addElement("varequal");
        varequal.addAttribute("respident", getIdent());
        varequal.addAttribute("case", "Yes");
        varequal.addText(tmpChoice.getIdent());
        break;
    } // for loop

    // check if conditionvar has correct value
    if (conditionvar.elements().size() == 0) {
        resprocessingXML.remove(respcondition_correct);
        return;
    }

    final Element setvar = respcondition_correct.addElement("setvar");
    setvar.addAttribute("varname", "SCORE");
    setvar.addAttribute("action", "Set");
    setvar.addText("" + getSingleCorrectScore());

    // Use mastery feedback
    QTIEditHelperEBL.addFeedbackMastery(respcondition_correct);
}
 
Example 17
Source File: XMLUtil.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 创建XML文件
 * @return
 */
private static Document testCreateXMLFile() {
    // 使用DocumentHelper.createDocument方法建立一个文档实例
    Document document = DocumentHelper.createDocument();
    // 使用addElement方法方法创建根元素
    Element catalogElement = document.addElement("catalog");
    // 使用addComment方法方法向catalog元素添加注释
    catalogElement.addComment("使用addComment方法方法向catalog元素添加注释");
    // 使用addProcessInstruction向catalog元素增加处理指令
    catalogElement.addProcessingInstruction("target", "text");

    // 使用addElement方法向catalog元素添加journal子元素
    Element journalElement = catalogElement.addElement("journal");
    // 使用addAttribute方法向journal元素添加title和publisher属性
    journalElement.addAttribute("title", "XML Zone");
    journalElement.addAttribute("publisher", "Willpower Co");

    // 使用addElement方法向journal元素添加article子元素
    Element articleElement = journalElement.addElement("article");
    // 使用addAttribute方法向article元素添加level和date属性
    articleElement.addAttribute("level", "Intermediate");
    articleElement.addAttribute("date", "July-2006");

    // 使用addElement方法向article元素添加title子元素
    Element titleElement = articleElement.addElement("title");
    // 使用setText方法设置title子元素的值
    titleElement.setText("Dom4j Create XML Schema");

    // 使用addElement方法向article元素添加authorElement子元素
    Element authorElement = articleElement.addElement("author");

    // 使用addElement方法向author元素添加firstName子元素
    Element firstName = authorElement.addElement("fistname");
    // 使用setText方法设置firstName子元素的值
    firstName.setText("Yi");

    // 使用addElement方法向author元素添加lastname子元素
    Element lastName = authorElement.addElement("lastname");
    // 使用setText方法设置lastName子元素的值
    lastName.setText("Qiao");

    return document;
}
 
Example 18
Source File: ModifyRequestDsml.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Element toDsml( Element root )
{
    Element element = super.toDsml( root );

    ModifyRequest request = getDecorated();

    // Dn
    if ( request.getName() != null )
    {
        element.addAttribute( "dn", request.getName().getName() );
    }

    // Modifications
    Collection<Modification> modifications = request.getModifications();

    for ( Modification modification : modifications )
    {
        Element modElement = element.addElement( "modification" );

        if ( modification.getAttribute() != null )
        {
            modElement.addAttribute( "name", modification.getAttribute().getId() );

            for ( Value value : modification.getAttribute() )
            {
                if ( value.getString() != null )
                {
                    if ( ParserUtils.needsBase64Encoding( value.getString() ) )
                    {
                        Namespace xsdNamespace = new Namespace( "xsd", ParserUtils.XML_SCHEMA_URI );
                        Namespace xsiNamespace = new Namespace( "xsi", ParserUtils.XML_SCHEMA_INSTANCE_URI );
                        element.getDocument().getRootElement().add( xsdNamespace );
                        element.getDocument().getRootElement().add( xsiNamespace );

                        Element valueElement = modElement.addElement( "value" ).addText(
                            ParserUtils.base64Encode( value.getString() ) );
                        valueElement.addAttribute( new QName( "type", xsiNamespace ), "xsd:"
                            + ParserUtils.BASE64BINARY );
                    }
                    else
                    {
                        modElement.addElement( "value" ).setText( value.getString() );
                    }
                }
            }
        }

        ModificationOperation operation = modification.getOperation();

        if ( operation == ModificationOperation.ADD_ATTRIBUTE )
        {
            modElement.addAttribute( "operation", "add" );
        }
        else if ( operation == ModificationOperation.REPLACE_ATTRIBUTE )
        {
            modElement.addAttribute( "operation", "replace" );
        }
        else if ( operation == ModificationOperation.REMOVE_ATTRIBUTE )
        {
            modElement.addAttribute( "operation", "delete" );
        }
        else if ( operation == ModificationOperation.INCREMENT_ATTRIBUTE )
        {
            modElement.addAttribute( "operation", "increment" );
        }
    }

    return element;
}
 
Example 19
Source File: ActionNodeDef.java    From EasyML with Apache License 2.0 4 votes vote down vote up
private void createProperty(Element root, String name, String value) {
	Element property = root.addElement("property");
	generateElement(property, "name", name);
	generateElement(property, "value", value);
}
 
Example 20
Source File: FIBQuestion.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Render XML
 */
public void addToElement(final Element root) {
    final Element presentationXML = root.addElement("presentation");
    presentationXML.addAttribute("label", "notset");
    // presentation
    final Element flowXML = presentationXML.addElement("flow");
    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final FIBResponse fibcontent = (FIBResponse) i.next();
        if (fibcontent.getType().equals(FIBResponse.TYPE_CONTENT)) {
            final Material mat = fibcontent.getContent();
            if (mat.getElements().isEmpty()) {
                // the flow cannot be empty -> add dummy material element
                flowXML.addElement("material").addElement("mattext").addCDATA("");
            } else {
                mat.addToElement(flowXML);
            }
        } else if (fibcontent.getType().equals(FIBResponse.TYPE_BLANK)) {
            final Element response_str = flowXML.addElement("response_str");
            response_str.addAttribute("ident", fibcontent.getIdent());
            response_str.addAttribute("rcardinality", "Single");

            final Element render_fib = response_str.addElement("render_fib");
            render_fib.addAttribute("columns", String.valueOf(fibcontent.getSize()));
            render_fib.addAttribute("maxchars", String.valueOf(fibcontent.getMaxLength()));

            final Element flow_label = render_fib.addElement("flow_label");
            flow_label.addAttribute("class", "Block");
            final Element response_lable = flow_label.addElement("response_label");
            response_lable.addAttribute("ident", fibcontent.getIdent());
            response_lable.addAttribute("rshuffle", "Yes");
        }
    }

    // resprocessing
    final Element resprocessingXML = root.addElement("resprocessing");

    // outcomes
    final Element decvar = resprocessingXML.addElement("outcomes").addElement("decvar");
    decvar.addAttribute("varname", "SCORE");
    decvar.addAttribute("vartype", "Decimal");
    decvar.addAttribute("defaultval", "0");
    decvar.addAttribute("minvalue", "" + getMinValue());
    float maxScore = QTIEditHelperEBL.calculateMaxScore(this);
    maxScore = maxScore > getMaxValue() ? getMaxValue() : maxScore;
    decvar.addAttribute("maxvalue", "" + maxScore);
    decvar.addAttribute("cutvalue", "" + maxScore);

    // respcondition
    // correct

    if (isSingleCorrect()) {
        buildRespconditionFIBSingle(resprocessingXML);
        buildRespcondition_fail(resprocessingXML, true);
    } else {
        buildRespconditionFIBMulti(resprocessingXML);
        buildRespcondition_fail(resprocessingXML, false);
    }

    // hint
    if (getHintText() != null) {
        QTIEditHelperEBL.addHintElement(root, getHintText());
    }

    // solution
    if (getSolutionText() != null) {
        QTIEditHelperEBL.addSolutionElement(root, getSolutionText());
    }

    // Feedback for all other cases eg. none has been answered at all
    final Element incorrect = resprocessingXML.addElement("respcondition");
    incorrect.addAttribute("title", "Fail");
    incorrect.addAttribute("continue", "Yes");
    incorrect.addElement("conditionvar").addElement("other");
    final Element setvar = incorrect.addElement("setvar");
    setvar.addAttribute("varname", "SCORE");
    setvar.addAttribute("action", "Set");
    setvar.setText("0");
    QTIEditHelperEBL.addFeedbackFail(incorrect);
    QTIEditHelperEBL.addFeedbackHint(incorrect);
    QTIEditHelperEBL.addFeedbackSolution(incorrect);
}