源代碼 http://www.tkk7.com/Files/zhaochengming/dom4j.rar
<一>.dom方式
個(gè)人感覺如果是讀取修改配置文件等對xml文件比較小的情況下,建議使用dom的方式,如果是用xml來傳輸數(shù)據(jù),主要是讀取的作用,建議使用sax
我們先定義一個(gè)xml文件,后面的sax方式也用這個(gè)方式,
person.xml
<?xml version="1.0" encoding="utf-8"?><學(xué)生信息>
<學(xué)生>
<編號>B0071423</編號>
<姓名>周星馳</姓名>
<年齡>23</年齡>
</學(xué)生>
<學(xué)生>
<編號 id="100">B0071424</編號>
<姓名>Tom.Bluser</姓名>
<年齡>24</年齡>
</學(xué)生>
<班級 id="00222" name="class">搞笑班</班級>
</學(xué)生信息>
代碼如下,用的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();
// 循環(huán)遍歷根元素里面的所有學(xué)生元素
for (Iterator i = studentsInfo.elementIterator("學(xué)生"); i.hasNext();) {
Element student = (Element) i.next();
// 輸出“編號”元素標(biāo)簽的內(nèi)容
System.out.println(student.elementTextTrim("編號"));
System.out.println(student.elementTextTrim("姓名"));
System.out.println(student.elementTextTrim("年齡"));
// 如果當(dāng)前學(xué)生項(xiàng)里面的編號是“002”的話,就把姓名標(biāo)簽的內(nèi)容更改為“002孫宇”
if (student.elementTextTrim("編號").equals("002")) {
student.selectSingleNode("姓名").setText("002孫宇");
}
}
// 直接輸出班級元素標(biāo)簽的內(nèi)容
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();// 關(guān)閉輸出流
}
}
<二>.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();
// 設(shè)置設(shè)置名稱空間敏感性選項(xiàng),關(guān)掉確認(rèn)選項(xiàng)
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("學(xué)生信息")) {
System.out.println("開始讀學(xué)生信息...");
this.studentsInfo.setNodeName("學(xué)生信息");
tempNode = this.studentsInfo;
} else if (name.equals("學(xué)生") || 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("學(xué)生") || name.equals("班級")) {
this.childNode = null;
}
}
}
</script>