JAXP開發工具包j2se的一部分,它由javax.xml、org.w3c.dom、org.xml.sax 包及其子包組成。
在javax.xml.parsers包中,定義了幾個工廠類,通過調用這幾個工廠類,可以建立dom和sax解析器,對XML文檔進行解析。
自己嘗試使用了DOM解析器來解析XML文檔,給大家分享下經驗,第一次寫技術BLOG,有缺陷的地方還望大家拍磚。
具體代碼和注釋如下:
1、建立一個XmlUtils類,這裡面寫2個方法,一個方法是用來得到Document對象,一個方法用來将記憶體中的資料寫入指定XML文檔。
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XmlUtils {
//定義文檔路徑
public static String filename = "src/test.xml";
//擷取解析後的XML文檔方法
public static Document getDocument() throws Exception {
//擷取Dom工廠執行個體
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//擷取Dom解析器
DocumentBuilder builder = factory.newDocumentBuilder();
//解析所需文檔
return builder.parse(filename);
}
//将記憶體中的資料寫入XML中
public static void document2Xml(Document document) throws Exception{
//擷取工廠執行個體
TransformerFactory tffactory=TransformerFactory.newInstance();
//擷取Transformer對象
Transformer tf =tffactory.newTransformer();
//調用transform(Source xmlSource, Result outputTarget) 方法,将記憶體資料寫入指定XML
tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream(filename)));
}
}
2、用XML作為資料庫存儲學生的資訊(姓名,城市和身份證号),建立一個StudentBean類,來擷取Student對象
public class StudentBean {
private String name;
private double idcard;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getIdcard() {
return idcard;
}
public void setIdcard(double idcard) {
this.idcard = idcard;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
3、StudentDao類來處理對XML增删查的功能
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import cn.shenyoujun.Bean.StudentBean;
import cn.shenyoujun.Exception.StudentNotExistException;
import cn.shenyoujun.XmlUtils.XmlUtils;
public class StudentDao {
//增加學生資訊方法
public void add(StudentBean student) {
try {
Document document = XmlUtils.getDocument();
Element student_tag = document.createElement("student");
student_tag.setAttribute("name", student.getName());
Element idcard = document.createElement("idcard");
Element city = document.createElement("city");
idcard.setTextContent(student.getIdcard() + "");
city.setTextContent(student.getCity());
student_tag.appendChild(idcard);
student_tag.appendChild(city);
document.getElementsByTagName("exam").item(0)
.appendChild(student_tag);
XmlUtils.document2Xml(document);
System.out.print("添加成功");
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
//删除學生資訊方法
public void remove(String name) throws StudentNotExistException {
try {
Document document = XmlUtils.getDocument();
NodeList list = document.getElementsByTagName("student");
StudentBean sb = new StudentBean();
for (int i = 0; i < list.getLength(); i++) {
Element student = (Element) list.item(i);
if (student.getAttribute("name").equals(name)) {
list.item(i).getParentNode().removeChild(list.item(i));
XmlUtils.document2Xml(document);
}
}
throw new StudentNotExistException(name + "不存在!");
} catch (StudentNotExistException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//尋找學生資訊方法
public StudentBean search(String name) {
try {
Document document = XmlUtils.getDocument();
NodeList list = document.getElementsByTagName("student");
StudentBean sb = new StudentBean();
for (int i = 0; i < list.getLength(); i++) {
Element student = (Element) list.item(i);
if (student.getAttribute("name").equals(name)) {
sb.setName(name);
sb.setIdcard(Double.parseDouble(student
.getElementsByTagName("idcard").item(0)
.getTextContent()));
sb.setCity(student.getElementsByTagName("city").item(0)
.getTextContent());
return sb;
}
}
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
}
4、最後寫個單元測試類,來測試這些功能
package Junit;
import org.junit.Test;
import cn.shenyoujun.Bean.StudentBean;
import cn.shenyoujun.Dao.StudentDao;
import cn.shenyoujun.Exception.StudentNotExistException;
public class TestStudentDao {
@Test
public void testAdd() {
StudentDao sd = new StudentDao();
StudentBean s = new StudentBean();
s.setName("張三");
s.setCity("nanjing");
s.setIdcard(2);
sd.add(s);
}
@Test
public void testSearch(){
StudentDao sd = new StudentDao();
String name="張三";
StudentBean sb=sd.search(name);
System.out.print(sb.getName()+" "+sb.getCity()+" "+sb.getIdcard());
}
@Test
public void testRemove(){
StudentDao sd = new StudentDao();
String name="張三";
try {
sd.remove(name);
} catch (StudentNotExistException e) {
e.printStackTrace();
}
}
}
總結下Dom解析的優劣點:
使用Dom解析的原理是将所有的标簽和熟悉都解析成對象存入到記憶體中,優點是對做增删改的操作比較友善
但是缺點是對記憶體消耗大,不宜做查詢。