xml文件的书写及读取books.xml文件生成Book类
生活随笔
收集整理的這篇文章主要介紹了
xml文件的书写及读取books.xml文件生成Book类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
books.xml文件的書寫:
<?xml version="1.0" encoding="UTF-8" ?> <!-- <?xml version="1.0" encoding="UTF-8" ?> 以上內容就是xml文件的聲明, version="1.0" version表示xml的版本 encoding="utf-8" encoding表示xml文件本身的編碼 --> <books><book sn="SN321324"><!-- book表示一個圖書信息 sn屬性表示圖書序列號--><name>時間簡歷</name><!--name標簽表示書名 --><author>陳彬<![CDATA[>>>><<<<<陳彬]]></author><!--auther表示作者--><price>23</price><!--price表示價格--></book><book sn="SN238238"><name>從Java入門到放棄</name><author>康師傅</author><price>22</price></book> </books>Book類的書寫:
package com.atshangqiu.web;import java.math.BigDecimal;public class Book {private String sn;private String name;private BigDecimal price;private String auther;@Overridepublic String toString() {return "Book{" +"sn='" + sn + '\'' +", name='" + name + '\'' +", price=" + price +", auther='" + auther + '\'' +'}';}public Book() {}public Book(String sn, String name, BigDecimal price, String auther) {this.sn = sn;this.name = name;this.price = price;this.auther = auther;}public String getSn() {return sn;}public void setSn(String sn) {this.sn = sn;}public String getName() {return name;}public void setName(String name) {this.name = name;}public BigDecimal getPrice() {return price;}public void setPrice(BigDecimal price) {this.price = price;}public String getAuther() {return auther;}public void setAuther(String auther) {this.auther = auther;} }Dom4jTest類的書寫:
package com.atshangqiu.web;import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.junit.Test; import org.xml.sax.XMLReader;import java.math.BigDecimal; import java.util.List;/* 讀取books.xml文件生成Book類*/ public class Dom4jTest {@Testpublic void test() throws Exception {//1.讀取books.xml文件SAXReader saxReader = new SAXReader();//在junit測試中,相對路徑是從模塊名開始算Document document = saxReader.read("src/books");//2.通過document對象獲取根元素Element rootElement = document.getRootElement();//3.通過根元素獲取book標簽對象//element(),elements()都是通過標簽名查找子元素List<Element> books = rootElement.elements("book");//4.遍歷,處理每個book標簽轉換為Book類for(Element book:books){//asXML是把標簽對象,轉換為標簽字符串//System.out.println(book.asXML());Element name = book.element("name");//getText(),可以獲取標簽中的文本內容String text = name.getText();String author = book.elementText("author");String price = book.elementText("price");String sn = book.attributeValue("sn");System.out.println(new Book(sn,text,new BigDecimal(price),author));}} }用到的jar包:
dom4j-1.6.1.jar
總結
以上是生活随笔為你收集整理的xml文件的书写及读取books.xml文件生成Book类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 清理oracle系统表空间,Oracle
- 下一篇: 小学交通安全教育课件PPT模板