Posted on 2006-11-10 08:53
久城 阅读(6203)
评论(1) 编辑 收藏 所属分类:
Java理解笔记
首先导入dom4j.jar包,这个包里面有我们创建XML文件需要用到的类,比如常用的有:
Document:
import org.dom4j.Document;
Import org.dom4j.DocumentHelper;
DocumentHelper.createDocument(); 获得文档对象
addElement方法增加根节点
getRootElement方法获得根节点
asXML方法将文档对象包含的内容转换为字符
addComment方法在增加注释
getPath方法获得路径,根节点为/
Element:
import org.dom4j.Elemet;
addElement方法增加子节点
addAttribute方法增加属性
getName方法获得节点名称
asXML方法将文档对象包含的内容转换为字符
addComment方法在增加注释
getPath方法获得路径
addText方法增加节点值
setText方法设置节点值
addNamespace方法增加命名空间
attributeCount方法获得属性个数
attributeValue方法获得属性值
elementText方法指定元素的值
Attribute:
Import org.dom4j.Attribute;
getName方法获得属性名称
getValue方法获得属性值
setValue方法设置属性值
Node:
import org.dom4j.Node;
Document和Element中selectSingleNode方法获得对象
setName方法设置节点名称
getText方法获得节点值
setText方法设置节点值
List,Iterator:
import java.util.List;
Document和Element中selectNodes方法获得对象
import java.util.Iterator;
List中iterator方法,Iterator中hasNext方法和next方法来获得节点或属性
XMLWriter:
import org.dom4j.io.XMLWriter;
Writer方法与OutputStream(FileOutputStream),Writer(FileWriter)
write方法写对象
close方法关闭写对象
OutputFormat:
import org.dom4j.io.OutputFormat;
setEncoding方法设置字符集
createCompactFormat方法为紧凑格式,默认
createPrettyFormat方法为缩进格式
SAXReader:
import org.dom4j.io.SAXReader ;
read方法与File
下面,我们用这些类来实现一下创建XML文件的简单过程:
1
package Test;
2
3
import java.io.*;
4
import org.dom4j.*;
5
import org.dom4j.io.*;
6
7
public class xmlTest
{
8
9
public void writeXML()
{
10
Document doc = org.dom4j.DocumentHelper.createDocument();
11
//创建节点操作对象
12
Element rootElement = doc.addElement("student");
13
//创建根节点对象rootElement,标签名为student
14
15
rootElement.setText("hello");
16
//对节点设置内容,后面读取XML文件的时候可以把他取出来
17
rootElement.addAttribute("id","030511111");
18
//设置节点属性
19
Element name = rootElement.addElement("name");
20
//添加子节点
21
name.setText("xiaozhang");
22
//设置子节点内容
23
Element age = rootElement.addElement("age");
24
age.setText("23");
25
26
try
{
27
OutputFormat fmt = new OutputFormat();
28
//创建输出格式对象
29
fmt.setEncoding("gb2312");
30
XMLWriter writer = new XMLWriter(fmt);
31
//以输出格式为参数,创建XML文件输出对象
32
OutputStream out = new FileOutputStream("d:\\test.xml");
33
//创建输出流..
34
writer.setOutputStream(out);
35
//设置输出流
36
writer.write(doc);
37
//输出doc对象,即形成XML文件
38
} catch (Exception e)
{
39
40
e.printStackTrace();
41
}
42
43
}
44
45
public void readXML()
{
46
SAXReader reader = new SAXReader();
47
//创建读取对象
48
Document doc;
49
try
{
50
doc = reader.read(new File("d:\\test.xml"));
51
//从test.xml文件中取得节点操作对象
52
Element name = doc.getRootElement();
53
//取得节点对象
54
System.out.println(name.getText());
55
//输出节点内容
56
} catch (Exception e)
{
57
e.printStackTrace();
58
}
59
}
60
61
public static void main(String[] args)
{
62
xmlTest s = new xmlTest();
63
s.writeXML();
64
s.readXML();
65
}
66
}
67
欢迎来访!^.^!
本BLOG仅用于个人学习交流!
目的在于记录个人成长.
所有文字均属于个人理解.
如有错误,望多多指教!不胜感激!