在項目中,我們很多都用到了xml文件,無論是參數配置還是與其它系統的數據交互。
今天就來講一下Java 中使用dom4j來操作XML文件。
我們需要引入的包:
1
//文件包
2
import java.io.ByteArrayOutputStream;
3
import java.io.File;
4
import java.io.FileWriter;
5
//工具包
6
import java.util.Iterator;
7
import java.util.List;
8
//dom4j包
9
import org.dom4j.Attribute;
10
import org.dom4j.Document;
11
import org.dom4j.DocumentHelper;
12
import org.dom4j.Element;
13
import org.dom4j.io.OutputFormat;
14
import org.dom4j.io.SAXReader;
15
import org.dom4j.io.XMLWriter;
1、將XML文件的內容轉化為String
1
/** *//**
2
* doc2String
3
* 將xml文檔內容轉為String
4
* @return 字符串
5
* @param document
6
*/
7
public static String doc2String(Document document)
8
{
9
String s = "";
10
try
11
{
12
//使用輸出流來進行轉化
13
ByteArrayOutputStream out = new ByteArrayOutputStream();
14
//使用GB2312編碼
15
OutputFormat format = new OutputFormat(" ", true, "GB2312");
16
XMLWriter writer = new XMLWriter(out, format);
17
writer.write(document);
18
s = out.toString("GB2312");
19
}catch(Exception ex)
20
{
21
ex.printStackTrace();
22
}
23
return s;
24
}
2、將符合XML格式的String 轉化為XML Document
1
/** *//**
2
* string2Document
3
* 將字符串轉為Document
4
* @return
5
* @param s xml格式的字符串
6
*/
7
public static Document string2Document(String s)
8
{
9
Document doc = null;
10
try
11
{
12
doc = DocumentHelper.parseText(s);
13
}catch(Exception ex)
14
{
15
ex.printStackTrace();
16
}
17
return doc;
18
}
3、將Document對象保存為一個xml文件到本地
1
/** *//**
2
* doc2XmlFile
3
* 將Document對象保存為一個xml文件到本地
4
* @return true:保存成功 flase:失敗
5
* @param filename 保存的文件名
6
* @param document 需要保存的document對象
7
*/
8
public static boolean doc2XmlFile(Document document,String filename)
9
{
10
boolean flag = true;
11
try
12
{
13
/**//* 將document中的內容寫入文件中 */
14
//默認為UTF-8格式,指定為"GB2312"
15
OutputFormat format = OutputFormat.createPrettyPrint();
16
format.setEncoding("GB2312");
17
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format);
18
writer.write(document);
19
writer.close();
20
}catch(Exception ex)
21
{
22
flag = false;
23
ex.printStackTrace();
24
}
25
return flag;
26
}
4、將xml格式的字符串保存為本地文件,如果字符串格式不符合xml規則,則返回失敗
1
/** *//**
2
* string2XmlFile
3
* 將xml格式的字符串保存為本地文件,如果字符串格式不符合xml規則,則返回失敗
4
* @return true:保存成功 flase:失敗
5
* @param filename 保存的文件名
6
* @param str 需要保存的字符串
7
*/
8
public static boolean string2XmlFile(String str,String filename)
9
{
10
boolean flag = true;
11
try
12
{
13
Document doc = DocumentHelper.parseText(str);
14
flag = doc2XmlFile(doc,filename);
15
}catch (Exception ex)
16
{
17
flag = false;
18
ex.printStackTrace();
19
}
20
return flag;
21
}
5、載入一個xml文檔
1
/** *//**
2
* load
3
* 載入一個xml文檔
4
* @return 成功返回Document對象,失敗返回null
5
* @param uri 文件路徑
6
*/
7
public static Document load(String filename)
8
{
9
Document document = null;
10
try
11
{
12
SAXReader saxReader = new SAXReader();
13
document = saxReader.read(new File(filename));
14
}
15
catch (Exception ex)
{
16
ex.printStackTrace();
17
}
18
return document;
19
}
6、演示String保存為xml文件
1
/** *//**
2
* xmlWriteDemoByString
3
* 演示String保存為xml文件
4
*/
5
public void xmlWriteDemoByString()
6
{
7
String s = "";
8
/** *//** xml格式標題 "<?xml version='1.0' encoding='GB2312'?>" 可以不用寫*/
9
s = "<config>\r\n"
10
+" <ftp name='DongDian'>\r\n"
11
+" <ftp-host>127.0.0.1</ftp-host>\r\n"
12
+" <ftp-port>21</ftp-port>\r\n"
13
+" <ftp-user>cxl</ftp-user>\r\n"
14
+" <ftp-pwd>longshine</ftp-pwd>\r\n"
15
+" <!-- ftp最多嘗試連接次數 -->\r\n"
16
+" <ftp-try>50</ftp-try>\r\n"
17
+" <!-- ftp嘗試連接延遲時間 -->\r\n"
18
+" <ftp-delay>10</ftp-delay>\r\n"
19
+" </ftp>\r\n"
20
+"</config>\r\n";
21
//將文件生成到classes文件夾所在的目錄里
22
string2XmlFile(s,"xmlWriteDemoByString.xml");
23
//將文件生成到classes文件夾里
24
string2XmlFile(s,"classes/xmlWriteDemoByString.xml");
25
}
7、演示手動創建一個Document,并保存為XML文件
1
/** *//**
2
* 演示手動創建一個Document,并保存為XML文件
3
*/
4
public void xmlWriteDemoByDocument()
5
{
6
/** *//** 建立document對象 */
7
Document document = DocumentHelper.createDocument();
8
/** *//** 建立config根節點 */
9
Element configElement = document.addElement("config");
10
/** *//** 建立ftp節點 */
11
configElement.addComment("東電ftp配置");
12
Element ftpElement = configElement.addElement("ftp");
13
ftpElement.addAttribute("name","DongDian");
14
/** *//** ftp 屬性配置 */
15
Element hostElement = ftpElement.addElement("ftp-host");
16
hostElement.setText("127.0.0.1");
17
(ftpElement.addElement("ftp-port")).setText("21");
18
(ftpElement.addElement("ftp-user")).setText("cxl");
19
(ftpElement.addElement("ftp-pwd")).setText("longshine");
20
ftpElement.addComment("ftp最多嘗試連接次數");
21
(ftpElement.addElement("ftp-try")).setText("50");
22
ftpElement.addComment("ftp嘗試連接延遲時間");
23
(ftpElement.addElement("ftp-delay")).setText("10");
24
/** *//** 保存Document */
25
doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml");
26
}
8、演示讀取文件的具體某個節點的值
1
/** *//**
2
* 演示讀取文件的具體某個節點的值
3
*/
4
public static void xmlReadDemo()
5
{
6
Document doc = load("classes/xmlWriteDemoByDocument.xml");
7
//Element root = doc.getRootElement();
8
/** *//** 先用xpath查找所有ftp節點 并輸出它的name屬性值*/
9
List list = doc.selectNodes("/config/ftp" );
10
Iterator it = list.iterator();
11
while(it.hasNext())
12
{
13
Element ftpElement = (Element)it.next();
14
System.out.println("ftp_name="+ftpElement.attribute("name").getValue());
15
}
16
/** *//** 直接用屬性path取得name值 */
17
list = doc.selectNodes("/config/ftp/@name" );
18
it = list.iterator();
19
while(it.hasNext())
20
{
21
Attribute attribute = (Attribute)it.next();
22
System.out.println("@name="+attribute.getValue());
23
}
24
/** *//** 直接取得DongDian ftp的 ftp-host 的值 */
25
list = doc.selectNodes("/config/ftp/ftp-host" );
26
it = list.iterator();
27
Element hostElement=(Element)it.next();
28
System.out.println("DongDian's ftp_host="+hostElement.getText());
29
}
9、修改或刪除某個值或屬性
1
/** *//** ftp節點刪除ftp-host節點 */
2
ftpElement.remove(hostElement);
3
/** *//** ftp節點刪除name屬性 */
4
ftpElement.remove(nameAttribute);
5
/** *//** 修改ftp-host的值 */
6
hostElement.setText("192.168.0.1");
7
/** *//** 修改ftp節點name屬性的值 */
8
nameAttribute.setValue("ChiFeng");
posted on 2008-11-25 08:45
Vincent-chen 閱讀(367)
評論(0) 編輯 收藏 所屬分類:
XML