效果:
- <?xml version="1.0" encoding="UTF-8"?>
- <root>
- <author name="Kree" location="UK">Kree Strachan</author>
- <author name="King" location="US">King McWrirter</author>
- </root>
java实现代码:
- import java.io.FileWriter;
- 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 DWriter {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try {
- XMLWriter writer = new XMLWriter(new FileWriter("src/author.xml"));
- Document doc = createDoc();
- writer.write(doc);
- writer.close();
- // Pretty print the document to System.out
- // 设置了打印的格式,将读出到控制台的格式进行美化
- OutputFormat format = OutputFormat.createPrettyPrint();
- writer = new XMLWriter(System.out, format);
- writer.write(doc);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static Document createDoc() {
- Document doc = DocumentHelper.createDocument();
- Element root = doc.addElement("root");
- Element author1 = root.addElement("author").addAttribute("name",
- "Kree").addAttribute("location", "UK")
- .addText("Kree Strachan");
- Element author2 = root.addElement("author").addAttribute("name", "King")
- .addAttribute("location", "US").addText("King McWrirter");
- return doc;
- }
- }
转载于:https://blog.51cto.com/lossie/1077261