package test.fortest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class WriteJavaEntityToXMl { public static void main(String args[]) { //建立xml文件 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"); //用XMLWriter類寫xml文件 XMLWriter xmlWriter = null; //文件路徑 String outputPath = "D:"+File.separator + "ForLearn" + File.separator + "Example" + File.separator + "mavenEx" + File.separator + "exampleF" + File.separator + "src"+ File.separator + "main" + File.separator + "webapp" + File.separator + "WEB-INF" + File.separator + "authors.xml";; try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setLineSeparator("\r\n"); format.setEncoding("utf-8"); xmlWriter = new XMLWriter(new FileOutputStream(outputPath), format); xmlWriter.write(document); } catch (IOException exp) { exp.printStackTrace(); } finally { if(xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
輸出文件以下: java
authors.xml web
<?xml version="1.0" encoding="utf-8"?> <root> <author name="James" location="UK">James Strachan</author> <author name="Bob" location="US">Bob McWhirter</author> </root>