package anby.com;import java.io.File;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.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class ReadXml {public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException{Book book=new Book();List Books=new ArrayList();//擷取工廠執行個體 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(true); //通過工廠擷取DocumentBuilder執行個體 DocumentBuilder dbuilder=factory.newDocumentBuilder(); //擷取Dom Document document= dbuilder.parse("Book.xml"); //擷取下面的子節點 NodeList bookElement =document.getElementsByTagName("book"); //遍曆NodeList取值 for(int i=0;i<bookElement.getLength();i++) { Node node=bookElement.item(i);//擷取節點下的元素 Element bookEle=(Element)node;//將節點對象轉換為元素 book.setId( bookEle.getAttribute("id")) ;//擷取屬性 NodeList childList= node.getChildNodes(); for(int j=0;j<childList.getLength();j++) {// if(childList.item(j).getNodeName()==“title") //這樣可以避免null 指標異常 if( "titile".equals(childList.item(j).getNodeName()))//Node.getNodeName()擷取節點名稱 { book.setTitile(childList.item(j).getTextContent());//Node..getTextContent()擷取節點內容 } if("price".equals(childList.item(j).getNodeName())) { book.setPrice(childList.item(j).getTextContent()); } } System.out.println(book); } }}class Book{ String id; String titile;String price; public String getId() {return id;}public void setId(String id) {this.id = id;}public String getTitile() {return titile;}public void setTitile(String titile) {this.titile = titile;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}@Overridepublic String toString() {return "Book [id=" + id + ", titile=" + titile + ", price=" + price+ "]";}}