问 :DOM解析方式是怎样的?
Dom解析是将xml文件全部载入,组装成一颗dom树,然后通过节点以及节点之间的关系来解析xml文件
以下为代码示例:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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 javax.xml.transform.OutputKeys;
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.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DomResolve {
public static void main(String[] args) throws IOException{
String file = "file/books.xml";
InputStream inputStream = new FileInputStream(file);
DomResolve domResove = new DomResolve();
//1.解析xml文件
try {
List<Book> bookList = domResove.getBooks(inputStream);
for(Book book : bookList ){
System.out.println(book.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2.创建xml文件
domResove.creatXML();
}
public DocumentBuilder getDocumentBuilder(){
//创建DocumentBuilderFactory对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//创建DocumentBuilder对象
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return db;
}
/**
* Dom方式解析xml文件
* @param inputStream
* @return
* @throws Exception
*/
public List<Book> getBooks(InputStream inputStream) throws Exception{
List<Book> list = new ArrayList<Book>();
try {
//获得文档对象
Document doc = getDocumentBuilder().parse(inputStream);
//获得根元素
Element element = doc.getDocumentElement();
if(element.getNodeType() == Node.ELEMENT_NODE){
NodeList bookNode = element.getElementsByTagName("book");
for(int i = 0;i< bookNode.getLength();i++){
Element bookElement = (Element) bookNode.item(i);
Book book = new Book();
book.setId(Integer.parseInt(bookElement.getAttribute("id")));
NodeList childNodes = bookElement.getChildNodes();
for(int j = 0;j<childNodes.getLength();j++ ){
if(childNodes.item(j).getNodeType() == Node.ELEMENT_NODE){
if("bookName".equals(childNodes.item(j).getNodeName())){
book.setBookName(childNodes.item(j).getFirstChild().getNodeValue());
}else if("author".equals(childNodes.item(j).getNodeName())){
book.setAuthor(childNodes.item(j).getFirstChild().getNodeValue());
}else if("year".equals(childNodes.item(j).getNodeName())){
book.setYear(childNodes.item(j).getFirstChild().getNodeValue());
}
}
}//end j
list.add(book);
}//end i
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* Dom方式创建xml文件
*/
public void creatXML() throws FileNotFoundException{
DocumentBuilder db = getDocumentBuilder();
Document document = db.newDocument();
document.setXmlStandalone(true);//设置XML的standalone属性:(yes or no)
//创建根节点
Element bookstore= document.createElement("bookStore");
//添加子节点book
Element book=document.createElement("book");
//添加子节点name
Element name=document.createElement("name");
book.appendChild(name);
Element author=document.createElement("author");
book.appendChild(author);
Element year=document.createElement("year");
book.appendChild(year);
//添加子节点内容
name.setTextContent("冰与火之歌");
author.setTextContent("乔治马丁");
year.setTextContent("2004");
//添加节点属性
book.setAttribute("id", "1");
//将book子节点添加到bookstore中
bookstore.appendChild(book);
//将bookstore节点(已包含book)添加到document中
document.appendChild(bookstore);
//将内存中的文档树保存至xml文档树中
TransformerFactory tff = TransformerFactory.newInstance();
try {
Transformer tf = tff.newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("file/cdom.xml")));
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}