本帖最后由 jzwlove 于 2016-12-29 01:46 编辑
解析一个book.xml内容为[XML] 纯文本查看 复制代码 <?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="0001">
<title>水浒传</title>
<price>1220.58</price>
</book>
<book id="0002">
<title>西游记</title>
<price>2128.58</price>
</book>
</books>
创建的Book的javaBean类
[Java] 纯文本查看 复制代码 package cn.java9.beans;
public class Book {
private String id;
private String title;
private double price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Book(String id, String title, double price) {
this.id = id;
this.title = title;
this.price = price;
}
public Book() {
}
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", price=" + price + "]";
}
}
解析开始
[Java] 纯文本查看 复制代码 package cn.java9.xml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cn.java9.beans.Book;
public class DomDemo01 {
public static void main(String[] args) throws Exception {
getAllBook();
}
public static List<Book> getAllBook() throws Exception {
List<Book> bookList = new ArrayList<Book>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
Document doc = documentBuilder.parse("books.xml");
NodeList nodes = doc.getElementsByTagName("book");
for (int i = 0; i < nodes.getLength(); i++) {
Book book = new Book();
Node node = nodes.item(i);
Element ele = (Element) node;
String id = ele.getAttribute("id");
book.setId(id);
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
String nodeName = childNode.getNodeName();
if ("title".equals(nodeName)) {
String title = childNode.getTextContent();
book.setTitle(title);
}
if ("price".equals(nodeName)) {
double price = Double.parseDouble(childNode
.getTextContent());
book.setPrice(price);
}
}
bookList.add(book);
}
System.out.println(bookList);
return bookList;
}
}
|