`

java读取Xml

 
阅读更多
1.java代码

package com.cgm.domtest;

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;

public class PareDomBook {

public static void main(String[] args) {
List list = getAllBook();
for (int i = 0; i < list.size(); i++) {
Book book = (Book) list.get(i);
System.out.println(book.getId() + "---" + book.getTitle() + "---" + book.getPrice());
}
}

public static List getAllBook() {
List list = new ArrayList();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("book.xml");
NodeList boolNodeList = document.getElementsByTagName("book");
for (int i = 0; i < boolNodeList.getLength(); i++) {
Book book = new Book();
Node node = boolNodeList.item(i);
Element el = (Element) node;
String id = el.getAttribute("id");
NodeList chList = el.getChildNodes();
String title = "";
int price = 0;
for (int j = 0; j < chList.getLength(); j++) {
Node chiNode = chList.item(j);
String chiName = chiNode.getNodeName();
if (chiName != null) {
if ("title".equals(chiName)) {
title = chiNode.getTextContent();
}
if ("price".equals(chiName)) {
String priceStr = chiNode.getTextContent();
price = Integer.parseInt(priceStr);
}
}
}
book.setId(id);
book.setTitle(title);
book.setPrice(price);
list.add(book);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}

public static void bulder() {

}

}

javabean代码
package com.cgm.domtest;

public class Book {
private String id;
private String title;
private int 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 int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

}


xml代码
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="b001">
<title>java core</title>
<price>688</price>
</book>
<book id="b002">
<title>思想政治</title>
<price>515</price>
</book>
<book id="b003">
<title>世界历史</title>
<price>545</price>
</book>
<book id="b004">
<title>大学生物</title>
<price>512</price>
</book>
</books>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics