java對xml檔案操作的工具類__java

來源:互聯網
上載者:User

首先列出目錄結構及其檔案內的功能:

com.testxml           .main    //所有對象的入口,測試類別
          .books   //實體
          .boos.xml   //xml檔案
          .booksDao      //將實體中的值轉化為xml檔案,儲存到制定目錄下的xml檔案中
                         //解析xml檔案轉化為list<實體>
          .testxml  //未整合的對xml檔案的操作
          .xmlUtil       //xml工具類,建立document對象
                         //得到父節點的子節點的值,只限於父節點下面的子節點是末端元素
                         //將document對象寫入到指定的xml檔案中去

                         //刪除指定節點及其子節點

xml工具類代碼:

package com.testxml;import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Result;import javax.xml.transform.Source;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;public class xmlUtil {/** * 建立document對象 * @param 相對路徑 * @return * @throws Exception */public  static Document getDocument(String str) throws Exception{//擷取dom解析器工廠DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//擷取具體的解析器DocumentBuilder db = dbf.newDocumentBuilder();//解析xml檔案,擷取document對象Document document = db.parse(new File(str));return document;}/** * 得到父節點的子節點的值,只限於父節點下面的子節點是末端元素 * @param document   xml對象 * @param parentSrt  父元素 * @param childStr   子項目 * @param i   第幾個父元素,從0開始 * @return */public  static String getChildValue(Document document,String parentSrt,String childStr,int i){NodeList list = document.getElementsByTagName(parentSrt);    Element element = (Element) list.item(i);    if(element==null)    {    throw new NullPointerException("指定的父節點不存在");    }    String content = element.getElementsByTagName(childStr).item(0).getFirstChild().getNodeValue();return content;}/** * 將document對象寫入到指定的xml檔案中去 * @param document * @param str  xml所在目錄 * @throws Exception */ public  static void saveDocument(Document document,String str) throws Exception {    TransformerFactory transformerFactory = TransformerFactory.newInstance();          //step10:獲得一個Transformer對象          Transformer transformer = transformerFactory.newTransformer();          //step11:把document對象用一個DOMSource對象封裝起來          Source xmlSource = new DOMSource(document);          //step12:建立一個儲存目標對象          Result outputTarget = new StreamResult(new File(str));          //step13:產生相應的xml檔案          transformer.setOutputProperty("encoding", "UTF-8");        transformer.transform(xmlSource, outputTarget);   } /**  * 刪除指定節點及其子節點  * @param name  節點鍵  * @param str   xml檔案所在目錄  * @return  * @throws Exception  */ public  static boolean delete(Document document,String name,String str) throws Exception { boolean result = false;  NodeList nodeLists = document.getElementsByTagName(name);  int len=nodeLists.getLength(); //遍曆這個nodelist,每次都刪除nodelist的第一個,因為nodelist的size是不斷變化的 for(int i=0;i<len;i++) {  nodeLists.item(0).getParentNode().removeChild(nodeLists.item(0));  } xmlUtil.saveDocument(document, str); result=true; return result; } public static void main(String[] args) throws Exception {Document document=xmlUtil.getDocument("./src/testxml/books.xml");String value=xmlUtil.getChildValue(document,"book","title",1);System.out.println(value);}}


booksdao類代碼:

package com.testxml;import java.util.ArrayList;import java.util.List;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class booksDao {private Document document;public booksDao(String str) throws Exception{if(document==null){document = xmlUtil.getDocument(str);}}/** * 將實體中的值轉化為xml檔案,儲存到制定目錄下的xml檔案中 * @param books  實體 * @param str  存放xml檔案的路徑 * @return  是否儲存成功 * @throws Exception */ public boolean save(books books,String str) throws Exception {   if(books==null) { throw new IllegalArgumentException("實體類book不能為null");   } boolean result = false;   Element book = document.createElement("book");  //給擷取的book元素添加屬性 book.setAttribute("category", books.getCategory());   //建立元素,添加到book上面 Element title = document.createElement("title");   title.setTextContent(books.getTitle());  book.appendChild(title); Element author = document.createElement("author");   author.setTextContent(books.getAuthor()); book.appendChild(author);  //擷取根節點,根節點添加book元素 Node tempNode=document.getElementsByTagName("booklist").item(0); tempNode.appendChild(book);  xmlUtil.saveDocument(document, str); result=true; return result; }  /**  * 刪除指定節點及其子節點  * @param name  節點鍵  * @param str   xml檔案所在目錄  * @return  * @throws Exception  */ public void delete(String name,String str) throws Exception { boolean result=xmlUtil.delete(document, name, str); if(result==true) { System.out.println("刪除成功。"); } }  /**  * 解析xml檔案轉化為list<實體>  * @param name  * @return  */ public List<books> GetEntityList(String name) { List<books> booklists=new ArrayList<books>(); NodeList nodeLists = document.getElementsByTagName(name); for(int i=0;i<nodeLists.getLength();i++) {               Element e = (Element) nodeLists.item(i);              books books=new books();             books.setCategory(e.getAttribute("category"));             books.setTitle(e.getElementsByTagName("title").item(0).getTextContent());             books.setAuthor(e.getElementsByTagName("author").item(0).getTextContent());             booklists.add(books); }   return booklists; }}

books.xml檔案

<?xml version="1.0" encoding="UTF-8" standalone="no"?><booklist><book category="這是分類1"><title>這是標題1</title><author>這是作者1</author></book><book category="這是分類2"><title>這是標題2</title><author>這是作者2</author></book><book category="這是分類3"><title>這是標題3</title><author>這是作者3</author></book><book category="這是分類4"><title>這是標題4</title><author>這是作者4</author></book></booklist>
其他檔案代碼略。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.