源代码 http://www.blogjava.net/Files/zhaochengming/dom4j.rar
<一>.dom方式
个人感觉如果是读取修改配置文件等对xml文件比较小的情况下,建议使用dom的方式,如果是用xml来传输数据,主要是读取的作用,建议使用sax
我们先定义一个xml文件,后面的sax方式也用这个方式,
person.xml
<?xml version="1.0" encoding="utf-8"?><学生信息>
<学生>
<编号>B0071423</编号>
<姓名>周星驰</姓名>
<年龄>23</年龄>
</学生>
<学生>
<编号 id="100">B0071424</编号>
<姓名>Tom.Bluser</姓名>
<年龄>24</年龄>
</学生>
<班级 id="00222" name="class">搞笑班</班级>
</学生信息>
代码如下,用的dom4j解析器
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class ReadXml {
public static void main(String args[]) throws Exception{
SAXReader reader = new SAXReader();
// 声明文档对象
Document doc = null;
// 读取XML文档
doc = reader.read(new File("./config/person.xml"));
// 声明跟元素
Element studentsInfo = doc.getRootElement();
// 循环遍历根元素里面的所有学生元素
for (Iterator i = studentsInfo.elementIterator("学生"); i.hasNext();) {
Element student = (Element) i.next();
// 输出“编号”元素标签的内容
System.out.println(student.elementTextTrim("编号"));
System.out.println(student.elementTextTrim("姓名"));
System.out.println(student.elementTextTrim("年龄"));
// 如果当前学生项里面的编号是“002”的话,就把姓名标签的内容更改为“002孙宇”
if (student.elementTextTrim("编号").equals("002")) {
student.selectSingleNode("姓名").setText("002孙宇");
}
}
// 直接输出班级元素标签的内容
System.out.println(studentsInfo.selectSingleNode("班级").getText());
studentsInfo.selectSingleNode("班级").setText("真搞笑班");
XMLWriter writer = null;
OutputFormat format = OutputFormat.createPrettyPrint();
// 格式编码为“utf-8”
format.setEncoding("utf-8");
writer = new XMLWriter(new FileOutputStream(new File("./config/person.xml")), format);
writer.write(doc);// 写XML文档
writer.close();// 关闭输出流
}
}
<二>.sax方式
代码如下
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class TestSAXParsing {
public static void main(String args[]) throws Exception, SAXException {
SAXParserFactory factory = SAXParserFactory.newInstance();
// 设置设置名称空间敏感性选项,关掉确认选项
factory.setValidating(false);
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
MyHandler handler = new MyHandler();
parser.parse(new File("./config/person.xml"),handler);
handler.studentsInfo.toString();
}
}
class XmlNode {
private String nodeName;
private List<XmlNode> childs = new ArrayList<XmlNode>();
private HashMap<String,String> attributes = new HashMap<String,String>();
public String getNodeName() {
return nodeName;
}
public void addChild(XmlNode node) {
this.childs.add(node);
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public void addAttribute(String name, String value) {
this.attributes.put(name, value);
}
public String getAttribute(String name) {
return this.attributes.get(name);
}
public List<XmlNode> getChilds() {
return childs;
}
public void setChilds(List<XmlNode> childs) {
this.childs = childs;
}
public HashMap<String, String> getAttributes() {
return attributes;
}
public void setAttributes(HashMap<String, String> attributes) {
this.attributes = attributes;
}
public String toString() {
System.out.println(this.nodeName);
Iterator<String> key = this.attributes.keySet().iterator();
while (key.hasNext()) {
String str = key.next();
System.out.println("Attribuet["+str+","+this.attributes.get(str)+"]");
}
for (int i = 0; i < this.childs.size(); i++) {
XmlNode node = this.childs.get(i);
node.toString();
}
return super.toString();
}
}
class MyHandler extends DefaultHandler {
public XmlNode studentsInfo = new XmlNode();
private XmlNode childNode = null;
private XmlNode temp = null;
@Override
public void startElement(String uri, String localName, String name,
org.xml.sax.Attributes attributes) throws SAXException {
XmlNode tempNode = null;
if(name.equals("学生信息")) {
System.out.println("开始读学生信息...");
this.studentsInfo.setNodeName("学生信息");
tempNode = this.studentsInfo;
} else if (name.equals("学生") || name.equals("班级")) {
childNode = new XmlNode();
childNode.setNodeName("【"+name+"】");
this.studentsInfo.addChild(childNode);
tempNode = this.childNode;
} else if (name.equals("编号") || name.equals("姓名") || name.equals("年龄")) {
tempNode = new XmlNode();
tempNode.setNodeName(name);
childNode.addChild(tempNode);
} else {
return;
}
for (int i = 0; i < attributes.getLength(); i++) {
tempNode.addAttribute(attributes.getQName(i), attributes.getValue(i));
}
this.temp = tempNode;
}
public void characters(char[] ch, int start, int length)
throws SAXException {
String str = new String(ch,start,length);
if (str.trim().equals("")) {
return;
}
temp.addAttribute("text", str);
}
@Override
public void endElement(String namespaceURI, String localName, String name)
throws SAXException {
if (name.equals("学生") || name.equals("班级")) {
this.childNode = null;
}
}
}
</script>