DOM解析XML
本帖最后由 jzwlove 于 2016-12-29 01:46 编辑解析一个book.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类
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 ";
}
}
解析开始
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;
}
}
收藏
參考一下
3q 一般这种东西我都会用正则来做,代码量一下子少了N多。。。 谢谢分享!!! 解析xml我一般用xstream,xml转obj或者obj转xml都可以,比较方便. DOM解析大数据不行啊=== 这类工作我一般喜欢用python写,哈哈~ 推荐学习,但是我个人是最不喜欢DOM的,不是麻烦,而是API很怪
页:
[1]