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

The following examples show how to use org.dom4j.Document#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: Dom4jUtils.java    From spring-boot-study with MIT License 6 votes vote down vote up
/**
 * 创建一个 xml 文档
 * */
public static Document createDocument() {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("root");

    Element author1 = root.addElement("author")
            .addAttribute("name", "James")
            .addAttribute("location", "UK")
            .addText("James Strachan");

    Element author2 = root.addElement("author")
            .addAttribute("name", "Bob")
            .addAttribute("location", "US")
            .addText("Bob McWhirter");

    return document;
}
 
Example 2
Source File: XmlUtils.java    From nbp with Apache License 2.0 6 votes vote down vote up
public Document loadConigXml(String filename) {
    Document document = null;
    Reader xmlReader = null;
    FileInputStream stream = null;
    try {
        SAXReader saxReader = new SAXReader();
        stream =  new FileInputStream(new File(filename));
        xmlReader = new InputStreamReader(stream, "UTF-8");
        document = saxReader.read(xmlReader);
    }
    catch (Exception ex) {
        _logger.error(String.format("the filename of document is %s, error [%s]" , filename
                ,ex.getMessage()));
        document = DocumentHelper.createDocument();
        document.addElement("ROOT");
    } finally {
        closeStream(xmlReader);
        closeStream(stream);
    }
    return document;
}
 
Example 3
Source File: XmlUtils.java    From nbp with Apache License 2.0 6 votes vote down vote up
public Document load(String filename) {
    Document document = null;
    Reader xmlReader = null;
    InputStream stream = null;
    try {
        SAXReader saxReader = new SAXReader();
        stream = getClass().getClassLoader().getResourceAsStream(filename);
        xmlReader = new InputStreamReader(stream, "UTF-8");
        document = saxReader.read(xmlReader);
    }
    catch (Exception ex) {
        _logger.error(String.format("the filename of document is %s, error [%s]" , filename
                ,ex.getMessage()));
        document = DocumentHelper.createDocument();
        document.addElement("ROOT");
    } finally {
        closeStream(xmlReader);
        closeStream(stream);
    }
    return document;
}
 
Example 4
Source File: PersistenceXmlWriter.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void write(Argument arg) throws Exception {
	try {
		Document document = DocumentHelper.createDocument();
		Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
		persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
				"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
		persistence.addAttribute("version", "2.0");
		for (Class<?> cls : scanContainerEntity(arg.getProject())) {
			Element unit = persistence.addElement("persistence-unit");
			unit.addAttribute("name", cls.getCanonicalName());
			unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
			Element provider = unit.addElement("provider");
			provider.addText(PersistenceProviderImpl.class.getCanonicalName());
			for (Class<?> o : scanMappedSuperclass(cls)) {
				Element mapped_element = unit.addElement("class");
				mapped_element.addText(o.getCanonicalName());
			}
			Element slice_unit_properties = unit.addElement("properties");
			Map<String, String> properties = new LinkedHashMap<String, String>();
			for (Entry<String, String> entry : properties.entrySet()) {
				Element property = slice_unit_properties.addElement("property");
				property.addAttribute("name", entry.getKey());
				property.addAttribute("value", entry.getValue());
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File(arg.getPath());
		XMLWriter writer = new XMLWriter(new FileWriter(file), format);
		writer.write(document);
		writer.close();
		System.out.println("create persistence.xml at path:" + arg.getPath());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 5
Source File: PublishUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * 生成单个文章发布文件
 * @param article 
 * @param publishPath
 * @return
 */
public static String publishOneArticle(Article article, String publishPath) {
       // 删除已发布的文章,如果有的话
       String pubUrl = article.getPubUrl();
       if(pubUrl != null) {
           new File(pubUrl).delete();
       }
       
	// 生成发布路径
	File publishDir = new File(publishPath);
	if (!publishDir.exists()) {
		publishDir.mkdirs();
	}
	
	Document doc = DocumentHelper.createDocument();
	doc.setXMLEncoding(ArticleHelper.getSystemEncoding()); //一般:windows “GBK” linux “UTF-8”
	Element articleNode = doc.addElement("Article");
	
       Map<String, Object> articleAttributes = article.getAttributes4XForm(); // 包含文章的所有属性
       articleAttributes.remove("content");
	addValue2XmlNode(articleNode, articleAttributes);
	
	Element contentNode = articleNode.addElement("content");
	contentNode.addCDATA(article.getContent());
       
	// 发布文章对文章附件的处理
	Element eleAtts = articleNode.addElement("Attachments");
       ArticleHelper.addPicListInfo(eleAtts, article.getAttachments());
       
       // 以 “栏目ID_文章ID.xml” 格式命名文章发布的xml文件
       String fileName = article.getChannel().getId() + "_" + article.getId() + ".xml";
	String filePathAndName = publishPath + "/" + fileName;
       FileHelper.writeXMLDoc(doc, filePathAndName);
	return filePathAndName;
}
 
Example 6
Source File: PersistenceXmlHelper.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static List<String> write(String path, List<String> entities) throws Exception {
	List<String> names = new ArrayList<>();
	String name = "";
	try {
		names.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
		names = ListTools.includesExcludesWildcard(names, entities, null);
		Document document = DocumentHelper.createDocument();
		Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
		persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
				"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
		persistence.addAttribute("version", "2.0");
		for (String className : names) {
			name = className;
			Class<? extends JpaObject> clazz = (Class<JpaObject>) Class.forName(className);
			Element unit = persistence.addElement("persistence-unit");
			unit.addAttribute("name", className);
			unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
			Element provider = unit.addElement("provider");
			provider.addText(PersistenceProviderImpl.class.getName());
			for (Class<?> o : JpaObjectTools.scanMappedSuperclass(clazz)) {
				Element mapped_element = unit.addElement("class");
				mapped_element.addText(o.getName());
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File(path);
		FileUtils.touch(file);
		XMLWriter writer = new XMLWriter(new FileWriter(file), format);
		writer.write(document);
		writer.close();
		return names;
	} catch (Exception e) {
		throw new Exception("write error.className:" + name, e);
	}
}
 
Example 7
Source File: Feature.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public static Element saveXml3(List<Feature> features) {
    Document document = XMLUtil.createDocument();
    Element rootElement = document.addElement("Features");
    createFeatureElement3(rootElement, features);
     
	return rootElement;
}
 
Example 8
Source File: TestSummaryCreatorTask.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Processes all input files and gathers the relevant data.
 * 
 * @return The Dom4j document object containing the summary
 */
private Document processInputFiles() throws IOException
{
	Document summaryDoc = DocumentHelper.createDocument();

	summaryDoc.addElement("summary");

	for (Iterator it = getInputFiles().iterator(); it.hasNext();)
	{
		processInputFile(summaryDoc, (File)it.next());
	}
	return summaryDoc;
}
 
Example 9
Source File: AcademicSessionSetupExport.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();
		
		Element root = document.addElement("sessionSetup");
		root.addAttribute("term", session.getAcademicTerm());
		root.addAttribute("year", session.getAcademicYear());
		root.addAttribute("campus", session.getAcademicInitiative());
		root.addAttribute("dateFormat", sDateFormat.toPattern());
        root.addAttribute("created", new Date().toString());
        
        exportSession(root, session);
        exportManagers(root, session);
        exportDepartments(root, session);
        exportSubjectAreas(root, session);
        exportSolverGroups(root, session);
        exportDatePatterns(root, session);
        exportTimePatterns(root, session);
        exportExaminationPeriods(root, session);
        exportAcademicAreas(root, session);
        exportAcademicClassifications(root, session);
        exportMajors(root, session);
        exportMinors(root, session);
        exportStudentGroups(root, session);
        exportStudentAccomodations(root, session);
        
		commitTransaction();
       } catch (Exception e) {
           fatal("Exception: "+e.getMessage(),e);
           rollbackTransaction();
       }
}
 
Example 10
Source File: LianlianBranchTest.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
private void writeXml(List<JSONArray> list) throws Exception {
	File file = new File(SAVE_PATH);
	if (file.exists())
		file.delete();

	// 生成一个文档
	Document document = DocumentHelper.createDocument();
	Element root = document.addElement("root");
	for (JSONArray jsonArray : list) {
		for (Object object : jsonArray) {
			JSONObject json = (JSONObject) object;
			System.out.println(json);
			Element element = root.addElement("branch");
			// 为cdr设置属性名和属性值
			element.addAttribute("branchId", json.getString("prcptcd").trim());// 支行行号
			element.addAttribute("bankCode", json.getString("bankCode").trim());// 银行类型
			element.addAttribute("cityCode", json.getString("cityCode").trim());// 城市代码
			element.addAttribute("branchName", json.getString("brabank_name").trim());// 支行名称
		}
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(SAVE_PATH)), "UTF-8"), format);
	// 写入新文件
	writer.write(document);
	writer.flush();
	writer.close();
}
 
Example 11
Source File: TestSummaryCreatorTask.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Processes all input files and gathers the relevant data.
 * 
 * @return The Dom4j document object containing the summary
 */
private Document processInputFiles() throws IOException
{
	Document summaryDoc = DocumentHelper.createDocument();

	summaryDoc.addElement("summary");

	for (Iterator it = getInputFiles().iterator(); it.hasNext();)
	{
		processInputFile(summaryDoc, (File)it.next());
	}
	return summaryDoc;
}
 
Example 12
Source File: XmlStreamTest.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testReadWriteComplexTypes()
{
  final XmlObjectReader reader = new XmlObjectReader();
  reader.initialize(TestObject2.class);
  final XmlObjectWriter writer = new XmlObjectWriter();
  final Document document = DocumentHelper.createDocument();
  final Element root = document.addElement("root");
  final TestObject2 testObject2 = new TestObject2();
  Element el = writer.write(root, testObject2);
  TestObject2 o2 = (TestObject2) reader.read(el);
  assertNull(o2.testObject);
  assertNull(o2.list);
  testObject2.testObject = create("ds", XmlConstants.MAGIC_STRING, "Hurzel", "", "Hurzel", "Hurzel", 5.0, 5.0, 0, 42);
  el = writer.write(root, testObject2);
  o2 = (TestObject2) reader.read(el);
  assertEquals("ds", o2.testObject.s1);
  assertNull(o2.list);
  testObject2.list = new ArrayList<TestObject>();
  el = writer.write(root, testObject2);
  o2 = (TestObject2) reader.read(el);
  assertEquals("ds", o2.testObject.s1);
  assertEquals(0, o2.list.size());
  testObject2.list.add(create("1", "", "", "", "", "", 0.0, 0.0, 0, 0));
  testObject2.list.add(create("2", "", "", "", "", "", 0.0, 0.0, 0, 0));
  testObject2.list.add(create("3", "", "", "", "", "", 0.0, 0.0, 0, 0));
  el = writer.write(root, testObject2);
  o2 = (TestObject2) reader.read(el);
  assertEquals("ds", o2.testObject.s1);
  assertEquals(3, o2.list.size());
  final Iterator<TestObject> it = o2.list.iterator();
  assertEquals("1", it.next().s1);
  assertEquals("2", it.next().s1);
  assertEquals("3", it.next().s1);
}
 
Example 13
Source File: AbstractWx.java    From pay-spring-boot with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 将map转换成符合微信xml通信协议的document
 * @param map
 * @return
 */
protected Document buildDocFromMap(Map<String, String> map){
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("xml");
    for(String key : map.keySet()){
        root.addElement(key).addCDATA(map.get(key));
    }

    return document;
}
 
Example 14
Source File: HQLExportXML.java    From unitime with Apache License 2.0 4 votes vote down vote up
@Override
public void export(ExportHelper helper) throws IOException {
	String s = helper.getParameter("id");
	if (s == null)
		throw new IllegalArgumentException("No report provided, please set the id parameter.");
	SavedHQL report = SavedHQLDAO.getInstance().get(Long.valueOf(s));
	if (report == null)
		throw new IllegalArgumentException("Report " + s + " does not exist.");

	helper.getSessionContext().checkPermission(report, Right.HQLReportEdit);

	helper.setup("text/xml", report.getName().replace('/', '-').replace('\\', '-').replace(':', '-') + ".xml",
			false);

	Document document = DocumentHelper.createDocument();
	document.addDocType("report", "-//UniTime//UniTime HQL Reports DTD/EN",
			"http://www.unitime.org/interface/Reports.dtd");
	Element reportEl = document.addElement("report");
	reportEl.addAttribute("name", report.getName());
	for (SavedHQL.Flag flag : SavedHQL.Flag.values()) {
		if (report.isSet(flag))
			reportEl.addElement("flag").setText(flag.name());
	}
	if (report.getDescription() != null)
		reportEl.addElement("description").add(new DOMCDATA(report.getDescription()));
	if (report.getQuery() != null)
		reportEl.addElement("query").add(new DOMCDATA(report.getQuery()));
       for (SavedHQLParameter parameter: report.getParameters()) {
       	Element paramEl = reportEl.addElement("parameter");
       	paramEl.addAttribute("name", parameter.getName());
       	if (parameter.getLabel() != null)
       		paramEl.addAttribute("label", parameter.getLabel());
       	paramEl.addAttribute("type", parameter.getType());
       	if (parameter.getDefaultValue() != null)
       		paramEl.addAttribute("default", parameter.getDefaultValue());
       }
	reportEl.addAttribute("created", new Date().toString());

	OutputStream out = helper.getOutputStream();
	new XMLWriter(out, OutputFormat.createPrettyPrint()).write(document);
}
 
Example 15
Source File: MainLayoutController.java    From javafx-TKMapEditor with GNU General Public License v3.0 4 votes vote down vote up
private Document createSaveDocument() {
	Document document = DocumentHelper.createDocument();
	Element map = document.addElement(XMLElements.ELEMENT_MAP);

	Element mapSetting = map.addElement(XMLElements.ELEMENT_MAP_SETTING);

	Element mapWidth = mapSetting.addElement(XMLElements.ELEMENT_MAP_WIDTH);
	mapWidth.setText(TiledMap.getInstance().getMapWidth() + "");

	Element mapHeight = mapSetting.addElement(XMLElements.ELEMENT_MAP_HEIGHT);
	mapHeight.setText(TiledMap.getInstance().getMapHeight() + "");

	Element tileWidth = mapSetting.addElement(XMLElements.ELEMENT_TILE_WIDTH);
	tileWidth.setText(TiledMap.getInstance().getTileWidth() + "");

	Element tileHeight = mapSetting.addElement(XMLElements.ELEMENT_TILE_HEIGHT);
	tileHeight.setText(TiledMap.getInstance().getTileHeight() + "");

	// 写入资源列表
	Element mapResource = map.addElement(XMLElements.ELEMENT_MAP_RESOURCE);
	List<AltasResource> resources = AltasResourceManager.getInstance().getResources();
	for (int i = 0; i < resources.size(); i++) {
		AltasResource altasResource = resources.get(i);
		Element resource = mapResource.addElement(XMLElements.ELEMENT_RESOURCE);
		Element resourceId = resource.addElement(XMLElements.ELEMENT_ALTAS_ID);
		resourceId.setText(altasResource.getAltasId());
		Element resourcePath = resource.addElement(XMLElements.ELEMENT_ALTAS_PATH);
		resourcePath.setText(altasResource.getPathStr());
	}

	Element mapData = map.addElement(XMLElements.ELEMENT_MAP_DATA);
	for (int i = 0; i < tiledMapLayerList.size(); i++) {
		TiledMapLayer mapLayer = tiledMapLayerList.get(i);
		Element layer = mapData.addElement(XMLElements.ELEMENT_MAP_LAYER);
		layer.addAttribute(XMLElements.ATTRIBUTE_NAME, mapLayer.getLayerName());
		layer.addAttribute(XMLElements.ATTRIBUTE_VISIBLE, String.valueOf(mapLayer.isVisible()));
		layer.addAttribute(XMLElements.ATTRIBUTE_ALPHA, mapLayer.getAlpha() + "");
		layer.addAttribute(XMLElements.ATTRIBUTE_COLLIDER, String.valueOf(mapLayer.isCollider()));
		layer.setText(mapLayer.toString());
	}

	Element tilePropertyElement = map.addElement(XMLElements.ELEMENT_MAP_PROPERTY);
	ArrayList<TileProperty> tileProperties = TiledMap.getInstance().getPropertyList();
	for (TileProperty tileProperty : tileProperties) {
		Element data = tilePropertyElement.addElement(XMLElements.ELEMENT_PROPERTY_DATA);
		data.addAttribute(XMLElements.ATTRIBUTE_COL, String.valueOf(tileProperty.getCol()));
		data.addAttribute(XMLElements.ATTRIBUTE_ROW, String.valueOf(tileProperty.getRow()));

		HashMap<String, String> valuesMap = tileProperty.getValueMap();
		Iterator<String> keys = valuesMap.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			String value = valuesMap.get(key);
			Element propertyElement = data.addElement(XMLElements.ELEMENT_PROPERTY);
			propertyElement.addAttribute(XMLElements.ATTRIBUTE_KEY, key);
			propertyElement.addAttribute(XMLElements.ATTRIBUTE_VALUE, value);
		}
	}

	return document;
}
 
Example 16
Source File: Dom4jUtil2.java    From egdownloader with GNU General Public License v2.0 4 votes vote down vote up
public static void createElement(Document doc, String ele){
	doc.addElement(ele);
}
 
Example 17
Source File: UnifiedXmlDataShapeSupport.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public DataShape createShapeFromRequest(final ObjectNode json, final T openApiDoc, final O operation) {
    final Document document = DocumentHelper.createDocument();

    final Element schemaSet = document.addElement("d:SchemaSet", SCHEMA_SET_NS);
    schemaSet.addNamespace(XmlSchemaHelper.XML_SCHEMA_PREFIX, XmlSchemaHelper.XML_SCHEMA_NS);

    final Element schema = XmlSchemaHelper.addElement(schemaSet, "schema");
    schema.addAttribute("targetNamespace", SYNDESIS_REQUEST_NS);
    schema.addAttribute("elementFormDefault", "qualified");

    final Element parametersSchema = createParametersSchema(openApiDoc, operation);

    final Map<String, SchemaPrefixAndElement> moreSchemas = new HashMap<>();

    final Element bodySchema = createRequestBodySchema(openApiDoc, operation, moreSchemas);

    if (bodySchema == null && parametersSchema == null) {
        return DATA_SHAPE_NONE;
    }

    final Element element = XmlSchemaHelper.addElement(schema, ELEMENT);
    element.addAttribute(NAME, "request");
    final Element sequence = XmlSchemaHelper.addElement(element, COMPLEX_TYPE, SEQUENCE);

    final Element additionalSchemas = schemaSet.addElement("d:AdditionalSchemas");

    if (parametersSchema != null) {
        final Element parameters = XmlSchemaHelper.addElement(sequence, ELEMENT);
        parameters.addNamespace("p", SYNDESIS_PARAMETERS_NS);
        parameters.addAttribute(REF, "p:parameters");

        additionalSchemas.add(parametersSchema.detach());
    }

    if (bodySchema != null) {
        final Element bodyElement = XmlSchemaHelper.addElement(sequence, ELEMENT);
        bodyElement.addAttribute(NAME, "body");

        final Element body = XmlSchemaHelper.addElement(bodyElement, COMPLEX_TYPE, SEQUENCE, ELEMENT);
        final String bodyTargetNamespace = bodySchema.attributeValue("targetNamespace");

        final String bodyElementName = bodySchema.element(ELEMENT).attributeValue(NAME);
        if (bodyTargetNamespace != null) {
            body.addNamespace("b", bodyTargetNamespace);
            body.addAttribute(REF, "b:" + bodyElementName);
        } else {
            body.addAttribute(REF, bodyElementName);
        }

        additionalSchemas.add(bodySchema.detach());
    }

    moreSchemas.values().forEach(e -> additionalSchemas.add(e.schema.detach()));

    final String xmlSchemaSet = XmlSchemaHelper.serialize(document);

    return new DataShape.Builder()//
        .kind(DataShapeKinds.XML_SCHEMA)//
        .name("Request")//
        .description("API request payload")//
        .specification(xmlSchemaSet)//
        .putMetadata(DataShapeMetaData.UNIFIED, "true")
        .build();
}
 
Example 18
Source File: CommonDao.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 生成XML importFile 导出xml工具类
 */
public HttpServletResponse createXml(ImportFile importFile) {
	HttpServletResponse response = importFile.getResponse();
	HttpServletRequest request = importFile.getRequest();
	try {
		// 创建document对象
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		// 创建根节点
		String rootname = importFile.getEntityName() + "s";
		Element rElement = document.addElement(rootname);
		Class entityClass = importFile.getEntityClass();
		String[] fields = importFile.getField().split(",");
		// 得到导出对象的集合
		List objList = loadAll(entityClass);
		Class classType = entityClass.getClass();
		for (Object t : objList) {
			Element childElement = rElement.addElement(importFile.getEntityName());
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i];
				// 第一为实体的主键
				if (i == 0) {
					childElement.addAttribute(fieldName, String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				} else {
					Element name = childElement.addElement(fieldName);
					name.setText(String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				}
			}

		}
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		File fileWriter = new File(ctxPath + "/" + importFile.getFileName());
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(fileWriter));

		xmlWriter.write(document);
		xmlWriter.close();
		// 下载生成的XML文件
		UploadFile uploadFile = new UploadFile(request, response);
		uploadFile.setRealPath(importFile.getFileName());
		uploadFile.setTitleField(importFile.getFileName());
		uploadFile.setExtend("bak");
		viewOrDownloadFile(uploadFile);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return response;
}
 
Example 19
Source File: DOM4JSerializer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static DOM4JSettingsNode createBlankSettings() {
    Document document = DocumentHelper.createDocument();
    Element rootElement = document.addElement("root");
    DOM4JSettingsNode settings = new DOM4JSettingsNode(rootElement);
    return settings;
}
 
Example 20
Source File: CommonDao.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 生成XML importFile 导出xml工具类
 */
public HttpServletResponse createXml(ImportFile importFile) {
	HttpServletResponse response = importFile.getResponse();
	HttpServletRequest request = importFile.getRequest();
	try {
		// 创建document对象
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		// 创建根节点
		String rootname = importFile.getEntityName() + "s";
		Element rElement = document.addElement(rootname);
		Class entityClass = importFile.getEntityClass();
		String[] fields = importFile.getField().split(",");
		// 得到导出对象的集合
		List objList = loadAll(entityClass);
		Class classType = entityClass.getClass();
		for (Object t : objList) {
			Element childElement = rElement.addElement(importFile.getEntityName());
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i];
				// 第一为实体的主键
				if (i == 0) {
					childElement.addAttribute(fieldName, String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				} else {
					Element name = childElement.addElement(fieldName);
					name.setText(String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
				}
			}

		}
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		File fileWriter = new File(ctxPath + "/" + importFile.getFileName());
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(fileWriter));

		xmlWriter.write(document);
		xmlWriter.close();
		// 下载生成的XML文件
		UploadFile uploadFile = new UploadFile(request, response);
		uploadFile.setRealPath(importFile.getFileName());
		uploadFile.setTitleField(importFile.getFileName());
		uploadFile.setExtend("bak");
		viewOrDownloadFile(uploadFile);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return response;
}