java之Dom執行個體(W3cDom)

來源:互聯網
上載者:User
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+ "]";}}

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.