DOM解析是xml文件解析的一种,它是一次性加载文件的所有内容,属于文档驱动的解析。具体实现如下
package com.example.parse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.example.bean.Books;
public class DOMParse implements IParse {
private List<Books> l;
@Override
public List<Books> parse(InputStream is) {
l = new ArrayList<Books>();
try {
// 得到工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 创建DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// Document对象
Document parse = builder.parse(is);
// 得到根节点
Element element = parse.getDocumentElement();
// 通过根节点获得所有的图书
NodeList list = element.getElementsByTagName("book");
for (int i = 0; i < list.getLength(); i++) {
Books books = new Books();
// 获得单个book节点
Node node = list.item(i);
// 获得book节点下的子节点
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
// 获得单个节点
Node node2 = childNodes.item(j);
// 取得子节点的名称
String nodeName = node2.getNodeName();
// 判断取得子节点的名称
if ("name".equalsIgnoreCase(nodeName)) {
// 如果子节点的名称是所需要的那么就得到节点的值
String name = node2.getFirstChild().getNodeValue();
books.setName(name);
} else if ("author".equalsIgnoreCase(nodeName)) {
// 如果子节点的名称是所需要的那么就得到节点的值
String author = node2.getFirstChild().getNodeValue();
books.setAuthor(author);
} else if ("price".equalsIgnoreCase(nodeName)) {
// 如果子节点的名称是所需要的那么就得到节点的值
String price = node2.getFirstChild().getNodeValue();
books.setPrice(price);
}
}
l.add(books);
}
} catch (Exception e) {
e.printStackTrace();
}
return l;
}
}