java之Dom实例(W3cDom)
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") //这样可以避免空指针异常 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; } @Override public String toString() { return "Book [id=" + id + ", titile=" + titile + ", price=" + price + "]"; } }