java 创建XML文件

public void changeXML() {
           Document document
= DocumentHelper.createDocument();// 创建一个xml document对象
           Element books = document.addElement("books");// 创建根节点元素
          
// 给books添加注释
           books.addComment("—An XML Example");
          
// 使用addProcessingInstruction()方法增加一个处理指令
           books.addProcessingInstruction("target", "text");
          
// 在当前元素后增加一个子元素
           Element bookone = books.addElement("bookone");
          
// 设置当前元素的属性
           bookone.addAttribute("title", "XML study");
           bookone.addAttribute(
"publisher", "angellove workers");
           Element article
= bookone.addElement("article");
           article.addAttribute(
"level", "high");
           article.addAttribute(
"date", "December-2007");
           Element titleElement
= article.addElement("title");
          
// 设置当前元素的文本值,即是内容
           titleElement.setText("Java configuration with XML");
           Element authorElement
= article.addElement("author");
           Element firstNameElement
= authorElement.addElement("firstname");
           firstNameElement.setText(
"angel");
           Element lastNameElement
= authorElement.addElement("lastname");
           lastNameElement.setText(
"free");
          
// XML 声明 <?xml version="1.0" encoding="UTF-8"?> 自动添加到 XML 文档中。
           try {
            
// 创建一个xml写入流,将生成的xml文件写入指定的文件中
            
// 使用优雅的方式写入(一共有三种方式:普通方式,优雅方式和紧凑方式)
            
//紧凑方式写入format = OutputFormat.createCompactFormat();
             OutputFormat format = OutputFormat.createPrettyPrint();
             format.setEncoding(
"GBK");
             XMLWriter output
= new XMLWriter(
                
new FileWriter(new File("books.xml")), format);
             output.write(document);
             output.close();
           }
          
catch (IOException e) {
             System.out.println(e.getMessage());
           }
         }

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