dom4j創建xml


在前邊介紹SAX,PULL等等既然能解析,當然也能生成。不過這里介紹dom4j創建xml文件,簡單易懂。

dom4j是獨立的api,官網:http://www.dom4j.org/    可以去這下載jar包,里邊也有詳細的例子。。

在這里就進行簡單的介紹,夠用就行。。

 

1.創建document :

   Document document = DocumentHelper.createDocument();
      

2.添加節點

   // 創建根節點並添加進文檔

   Element root = document.addElement("persons");

 示例代碼:

import java.io.IOException;  
import java.io.StringWriter;  
import java.util.ArrayList;  
import java.util.List;  
  
import org.dom4j.Document;  
import org.dom4j.DocumentHelper;  
import org.dom4j.Element;  
import org.dom4j.io.OutputFormat;  
import org.dom4j.io.XMLWriter;  
  
  
public class XmlTest {  
     public XmlTest() {  
            // TODO Auto-generated constructor stub  
        }  
  
        public String createXML(int i){  
            String strXML = null;  
            Document document = DocumentHelper.createDocument();  
            // 創建根節點並添加進文檔  
            Element root = document.addElement("persons");  
            for(int j=0;j<i;j++){  
            Element person = root.addElement("person");  
            person.addAttribute("id", "100"+i).addAttribute("location", "中原"+i+"區");  
            Element name = person.addElement("name");  
            name.setText("小明"+i);  
            Element age = person.addElement("age");  
            age.addText("1"+i); //值!!  
            }  
            //--------  
            StringWriter strWtr = new StringWriter();  
            OutputFormat format = OutputFormat.createPrettyPrint();//Format格式!!  
            format.setEncoding("UTF-8");      
            XMLWriter xmlWriter =new XMLWriter(strWtr, format);  
            try {  
                xmlWriter.write(document);  
            } catch (IOException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
            }  
            strXML = strWtr.toString();  
            return strXML;  
       }  
        public static void main(String[] args) {  
            XmlTest test = new XmlTest();  
          
            String xmlStr = test.createXML(4);  
            System.out.println(xmlStr);  
        }  
}

  輸出結果:

簡單好用。。。。。。。。。

抓法請注明出處:http://www.cnblogs.com/jycboy/p/dom4j_xml.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM