前端之家收集整理的这篇文章主要介绍了
输出数据到xml文件(java实现),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
- package com.xiuye.utils;
-
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.util.Random;
-
- import org.dom4j.Document;
- import org.dom4j.DocumentHelper;
- import org.dom4j.Element;
- import org.dom4j.io.OutputFormat;
- import org.dom4j.io.XMLWriter;
-
- public class OutputEmpListXml {
-
- public static void main(String[] args) {
-
- // prepare char's array to generate random name
- char letters[] = new char[54];
- letters[0] = ' ';
- letters[1] = '-';
- // a~z
- for (int i = 0 + 2,j = 0; i < 26 + 2 && j < 26; i++,j++) {
- letters[i] = (char) ('a' + j);
- }
- // A~Z
- for (int i = 0 + 2 + 26,j = 0; i < 26 + 2 + 26 && j < 26; i++,j++) {
- letters[i] = (char) ('A' + j);
- }
-
- String sexs[] = { "man","woman" };
-
- Random rnd = new Random();
- // the whole xml file
- Document doc = DocumentHelper.createDocument();
- /**
- * only one root node,if not,IllegalAddException
- *
- */
- // node root
- Element root = doc.addElement("emp-list");
- for (int i = 0; i < 1000; i++) {
-
-
- // node emp
- Element emp = root.addElement("emp");
- int id = rnd.nextInt(9999999);
- // emp's attribute id
- emp.addAttribute("id",Integer.toString(id));
- // node name
- Element name = emp.addElement("name");
- name.setText(generateRandomName(letters));
- // node age
- Element age = emp.addElement("age");
- // node geneder
- Element geneder = emp.addElement("geneder");
- // node salary
- Element salary = emp.addElement("salary");
- // random age
- int ageInt = rnd.nextInt(100);
- age.setText(Integer.toString(ageInt));// first way "int -> String"
- // random sex
- int index = rnd.nextInt(2);
- geneder.setText(sexs[index]);
- // random salary
- int money = rnd.nextInt(10000000);
- salary.setText("" + money);// second way "int -> String"
- }
-
-
- try {
- FileOutputStream out = new FileOutputStream("EmpList.xml");
- OutputFormat format = OutputFormat.createPrettyPrint();
- XMLWriter xmlw = new XMLWriter(out,format);
- xmlw.write(doc);
-
- xmlw.close();
-
- } catch (FileNotFoundException e) {
-
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
-
- System.out.println("that's over!");
-
-
- }
-
- // get a simple random name
- private static String generateRandomName(char[] letters) {
- //String name = null;
- /**
- * name cannot be bull,beacause of
- * null += "ABC";=> nullABC
- * it's not my wanted.
- *
- */
- String name = "";
- int nameLength = (int) (Math.random() * letters.length) + 1;
- for (int i = 0; i < nameLength; i++) {
- int index = (int) (Math.random() * letters.length);
- name += "" + letters[index];
- }
-
- return name;
-
- }
-
- }