1. 程式人生 > >【Java Web】——配置檔案的格式之xml和properties的區分

【Java Web】——配置檔案的格式之xml和properties的區分

package testXMLDemo;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
/**
 * DOM4J 讀寫XML
 * Created by Cindy on 2016/9/16.
 */
public class dom4JDemo {

    /**
     * 生成XML檔案
*/ public static void generateDocument(){ Document document = DocumentHelper.createDocument(); //建立文件物件 Element catalogElement=document.addElement("catalog"); //建立元素 Element journalElement=catalogElement.addElement("journal"); Element articleElement=journalElement.addElement("article"); Element titleElement=articleElement.addElement("title"
); titleElement.setText("Java Configuration with XML Schema"); //設定元素內容值 Element authorElement=articleElement.addElement("author"); Element firstElement=authorElement.addElement("first"); firstElement.addText("Han"); Element lastElement=authorElement.addElement("last"); lastElement.addText("Cindy");
try{ XMLWriter output =new XMLWriter(new FileWriter(new File("D:/catalog.xml"))); //建立輸出物件 output.write(document); //將文件物件寫入輸出物件中 output.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } /** * 讀取XML檔案 * @throws DocumentException */ public static void getXML() throws DocumentException { SAXReader reader=new SAXReader(); Document document=reader.read(new File("src/sys-config.xml")); //獲取文件物件 Element node=document.getRootElement(); //獲得根節點 Element dbinfoElement=node.element("db-info"); //獲得元素節點 Element drivernameElement=dbinfoElement.element("driver-name"); Element urlElement=dbinfoElement.element("url"); Element usernameElement=dbinfoElement.element("user-name"); Element passwordElement=dbinfoElement.element("password"); String drivername=drivernameElement.getText(); //獲得節點內容 String url=urlElement.getText(); String username=usernameElement.getText(); String password=passwordElement.getText(); System.out.println(drivername); System.out.println(url); System.out.println(username); System.out.println(password);} public static void main(String [] args) throws DocumentException { //generateDocument(); getXML(); } }