下边内容内容是关于Java XML DOM解析范例的内容。
import java.io.InputStream;
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.NodeList;
import org.w3c.dom.Node;
import com.xtlh.cn.entity.Book;
public class DomParseService {
public List getBooks(InputStream inputStream) throws Exception{
List list = new ArrayList();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream);
Element element = document.getDocumentElement();
NodeList bookNodes = element.getElementsByTagName("book");
for(int i=0;i
Element bookElement = (Element) bookNodes.item(i);
Book book = new Book();
book.setId(Integer.parseInt(bookElement.getAttribute("id")));
NodeList childNodes = bookElement.getChildNodes();
for(int j=0;j
if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE){
if("name".equals(childNodes.item(j).getNodeName())){
book.setName(childNodes.item(j).getFirstChild().getNodeValue());
}else if("price".equals(childNodes.item(j).getNodeName())){
book.setPrice(Float.parseFloat(childNodes.item(j).getFirstChild().getNodeValue()));
}
}
list.add(book);
return list;
}
}
public class Book {
private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString(){
return this.id+":"+this.name+":"+this.price;
}
}
public class ParseTest extends TestCase{
public void testDom() throws Exception{
InputStream input = this.getClass().getClassLoader().getResourceAsStream("book.xml");
DomParseService dom = new DomParseService();
List books = dom.getBooks(input);
for(Book book : books){
System.out.println(book.toString());
}
}
}
xml文件描述:
thinking in java
85.5
Spring in Action
39.0