package com.jiang.dom;
import java.io.IOException;
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMTest {
public static void print(List<Book> temp){
for (Book book : temp) {
System.out.println(book);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Book> books = new ArrayList<Book>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse("E:/temp/books.xml");
NodeList bookList = document.getElementsByTagName("book");
for(int i = 0; i < bookList.getLength(); i++){
String id = null,name = null,author = null,year = null,price = null,language = null;
Node book = bookList.item(i);
NamedNodeMap attrs = book.getAttributes();
for(int j = 0; j < attrs.getLength(); j++){
Node attr = attrs.item(j);
id = attr.getNodeValue();
System.out.println(attr.getNodeName() + ":" + attr.getNodeValue());
}
NodeList childNodes = book.getChildNodes();
for(int k = 0; k < childNodes.getLength(); k++){
if(childNodes.item(k).getNodeType() == Node.ELEMENT_NODE){
Node childNode = childNodes.item(k);
System.out.println(childNode.getNodeName() + ":" + childNode.getFirstChild().getNodeValue());
String valueName = childNode.getNodeName();
if(valueName.equals("name")){
name = childNode.getFirstChild().getNodeValue();
}else if(valueName.equals("author")){
author = childNode.getFirstChild().getNodeValue();
}else if(valueName.equals("year")){
year = childNode.getFirstChild().getNodeValue();
}else if(valueName.equals("price")){
price = childNode.getFirstChild().getNodeValue();
}else if(valueName.equals("language")){
language = childNode.getFirstChild().getNodeValue();
}
}
}
Book b = new Book(id, name, author, year, price, language);
books.add(b);
}
DOMTest.print(books);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第一次发笔记 好怕怕 大牛勿喷
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦