JAXP,即Sun 的 Java API for XML ,是Sun推出操作XML的一套API,所有 parser 器类作为 com.sun.xml.parser
包.
位于API文档的javax.xml.parsers包中,如图所示:
重要的DocumentBuilderFactory XML解析工厂,静态newInstance方法可得到一个
工厂示例,通过实例调用newDocumentBuilder可得到文档解析器DocumentBuilder的实例
解析器通过parse方法得到Document 对象。Document 对象操作完成之后写入到xml文件是
需要用到另外的几个包 ,如左图所示:
通过TransformerFactory 调用newInstance得到一个工厂实例,工厂实例调用newTransformer
得到转换器,然后调用该转换器的transform方法可将Document 对象写入到xml文件
下面是对xml实现CRUD的实例
JaxpXMLUtil.java
package com.braden.util;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class JaxpXMLUtil {
String path = "";
public JaxpXMLUtil(String path) {
this.path = path;
}
public Document getDocument() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document = null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(path);
} catch (Exception e) {
throw new RuntimeException(e);
}
return document;
}
public boolean writeToXml(Document document, String path) {
boolean flag = false;
TransformerFactory tFactory = TransformerFactory.newInstance();
try {
Transformer tf = tFactory.newTransformer();
if (path != null && path != "") {
tf.transform(new DOMSource(document), new StreamResult(
new File(path)));
flag = true;
} else {
flag = false;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return flag;
}
public String getId() {
Document document = this.getDocument();
NodeList list = document.getDocumentElement().getChildNodes();
int id = 1;
if (list != null) {
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node node = list.item(i);
if (node.getNodeType()==Node.ELEMENT_NODE) {
id++;
}
}
}
return id+"";
}
}
UserDaoImpl.java
package com.braden.impl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.braden.dao.UserDao;
import com.braden.domain.User;
import com.braden.util.JaxpXMLUtil;
public class UserDaoImpl implements UserDao {
JaxpXMLUtil util = null;
public UserDaoImpl() {
util = new JaxpXMLUtil("src/user.xml");
}
public boolean delete(String id) {
boolean flag = false;
Document document = util.getDocument();
NodeList user_list = document.getElementsByTagName("user");
for (int i = 0; i < user_list.getLength(); i++) {
Element e = (Element) user_list.item(i);
if (e.getAttribute("id").equals(id)) {
Node node = user_list.item(i);
e.getParentNode().removeChild(node);
util.writeToXml(document, "src/user.xml");
flag = true;
}
}
return flag;
}
public User find(String id) {
Document document = util.getDocument();
NodeList user_list = document.getElementsByTagName("user");
User user = null;
for (int i = 0; i < user_list.getLength(); i++) {
Element e = (Element) user_list.item(i);
if (e.getAttribute("id").equals(id)) {
user = new User();
Node addressNode = e.getElementsByTagName("address").item(0);
Node bitthdayNode = e.getElementsByTagName("bitthday").item(0);
Node genderNode = e.getElementsByTagName("gender").item(0);
Node usernameNode = e.getElementsByTagName("username").item(0);
Node passwordNode = e.getElementsByTagName("password").item(0);
user.setAddress(addressNode.getTextContent());
user.setBitthday(bitthdayNode.getTextContent());
user.setGender(genderNode.getTextContent());
user.setUsername(usernameNode.getTextContent());
user.setPassword(passwordNode.getTextContent());
break ;
}
}
return user;
}
public boolean update(String id, String updateitem, String updateinfo) {
boolean flag = false;
Document document = util.getDocument();
NodeList user_list = document.getElementsByTagName("user");
for (int i = 0; i < user_list.getLength(); i++) {
Element e = (Element) user_list.item(i);
if (e.getAttribute("id").equals(id)) {
NodeList user_child_List = e.getChildNodes();
for (int j = 0; j < user_child_List.getLength(); j++) {
Node node_item = user_child_List.item(j);
if (node_item.getNodeName().equals(updateitem)) {
if (!node_item.getTextContent().equals(updateinfo)) {
node_item.setTextContent(updateinfo);
util.writeToXml(document, "src/user.xml");
flag = true;
}
}
}
}
}
return flag;
}
public boolean insert(User user) {
Document document = util.getDocument();
/* System.out.println(document.getDocumentURI()); */
Element node_user = document.createElement("user");
node_user.setAttribute("id", user.getId());
Element node_username = document.createElement("username");
node_username.setTextContent(user.getUsername());
Element node_id = document.createElement("id");
node_id.setTextContent(user.getId());
Element node_gender = document.createElement("gender");
node_gender.setTextContent(user.getGender());
Element node_password = document.createElement("password");
node_password.setTextContent(user.getPassword());
Element node_bitthday = document.createElement("bitthday");
node_bitthday.setTextContent(user.getBitthday());
Element node_address = document.createElement("address");
node_address.setTextContent(user.getAddress());
node_user.appendChild(node_username);
node_user.appendChild(node_bitthday);
node_user.appendChild(node_address);
node_user.appendChild(node_gender);
node_user.appendChild(node_password);
document.getDocumentElement().appendChild(node_user);
try {
util.writeToXml(document, "src/user.xml");
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
UserDaoImplTest.java
package com.braden.junit;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.braden.dao.UserDao;
import com.braden.domain.User;
import com.braden.impl.UserDaoImpl;
import com.braden.util.JaxpXMLUtil;
public class UserDaoImplTest {
static UserDao dao;
static JaxpXMLUtil util;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
dao = new UserDaoImpl();
util = new JaxpXMLUtil("src/user.xml");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDelete() {
if (dao.delete("2")) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
}
@Test
public void testFind() {
User user = dao.find("2");
if (user!=null) {
System.out.println(user.getPassword());
} else {
System.out.println("用户不存在");
}
}
@Test
public void testUpdate() {
if(dao.update("2", "password","lina")) {
System.out.println("更新成功");
} else {
System.out.println("更新失败");
}
}
@Test
public void testInsert() throws SAXException, IOException, ParserConfigurationException {
String id =util.getId();
User user = new User();
user.setAddress("beijing"+id+"beijing");
user.setBitthday("1984-09-03");
user.setId(id);
user.setUsername("braden_"+id);
user.setGender("female");
user.setPassword("123456");
try {
dao.insert(user);
System.out.println("user" + user.getId()+"添加成功!");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
User.java
package com.braden.domain;
public class User {
private String username;
private String id;
private String bitthday;
private String address;
private String gender;
private String password;
public User() {
super();
}
public User(String username, String id, String bitthday, String address,
String gender, String password) {
super();
this.username = username;
this.id = id;
this.bitthday = bitthday;
this.address = address;
this.gender = gender;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBitthday() {
return bitthday;
}
public void setBitthday(String bitthday) {
this.bitthday = bitthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
得到的xml文件
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- <!DOCTYPE user PUBLIC "//UNKNOWN/" "user.dtd"> -->
<users>
<user id="1">
<username>braden_1</username>
<bitthday>1984-09-03</bitthday>
<address>beijing1beijing</address>
<gender>female</gender>
<password>123456</password>
</user>
<user id="2">
<username>braden_2</username>
<bitthday>1984-09-03</bitthday>
<address>beijing2beijing</address>
<gender>female</gender>
<password>123456</password>
</user>
<user id="3">
<username>braden_3</username>
<bitthday>1984-09-03</bitthday>
<address>beijing3beijing</address>
<gender>female</gender>
<password>123456</password>
</user>
</users>