dom4j写xml

import java.io.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Document doc =  DocumentHelper.createDocument();
//创建数据指令对象
//doc.addProcessingInstruction("xml-stylesheet", "type = 'text/xsl' href = 'students.xsl'");

//处理指令没有执行
//Element root = doc.addElement("students");

//创建根元素

Element root = DocumentHelper.createElement("graph");
root.addAttribute("caption", "chinese");
root.addAttribute("xAxisName","Month");
root.addAttribute("yAxisName","Units");
root.addAttribute("decimalPrecision","0");
root.addAttribute("formatNumberScale","0");
doc.setRootElement(root);

String[] month={"Jan","Feb","Mar","Apr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dec"};
String[] value={"Jan","Feb","Mar","Apr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dec"};
String[] color={"Jan","Feb","Mar","Apr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dec"};

for(int i=0;i<12;i++){
Element set=root.addElement("set");
set.addAttribute("name", month[i]);
set.addAttribute("value", value[i]);
set.addAttribute("color", color[i]);
}

OutputFormat opf = new OutputFormat(" ",true);
opf.setEncoding("UTF-8");


PrintWriter pw = new PrintWriter(System.out);
try {
// doc.write(pw);
// pw.close();
XMLWriter xmlw = new XMLWriter(opf);
xmlw.write(doc);


File file = new File("students.xml");
FileWriter fw = new FileWriter(file);
XMLWriter output = new XMLWriter(fw);
output.write(doc);
output.close(); 
        // TODO code application logic here
    }
catch(Exception ex)
{}

    }
}

你可能感兴趣的:(xml,XSL)