欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java對(duì)XML文件增刪改查操作示例

 更新時(shí)間:2018年12月22日 11:27:38   作者:秋夜雨微涼  
這篇文章主要介紹了Java對(duì)XML文件增刪改查操作,結(jié)合完整實(shí)例形式分析了java針對(duì)xml格式數(shù)據(jù)的常見讀寫、增刪改查等操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Java對(duì)XML文件增刪改查操作。分享給大家供大家參考,具體如下:

xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book>
    <name>哈里波特</name>
    <price>10</price>
    <memo>這是一本很好看的書。</memo>
  </book>
  <book id="B02">
    <name>三國(guó)演義</name>
    <price>10</price>
    <memo>四大名著之一。</memo>
  </book>
  <book id="B03">
    <name>水滸</name>
    <price>6</price>
    <memo>四大名著之一。</memo>
  </book>
  <book id="B04">
    <name>紅樓</name>
    <price>5</price>
    <memo>四大名著之一。</memo>
  </book>
</books>

增刪改查 Test.java

import java.io.File;
import java.io.FileOutputStream;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
public class Test {
  public static void main(String[] args) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Element theBook = null, theElem = null, root = null;
    try {
      factory.setIgnoringElementContentWhitespace(true);
      DocumentBuilder db = factory.newDocumentBuilder();
      Document xmldoc = (Document) db.parse(new File("Test.xml"));
      root = xmldoc.getDocumentElement();
      // --- 新建一本書開始 ----
      theBook = xmldoc.createElement("book");
      theElem = xmldoc.createElement("name");
      theElem.setTextContent("新書");
      theBook.appendChild(theElem);
      theElem = xmldoc.createElement("price");
      theElem.setTextContent("20");
      theBook.appendChild(theElem);
      theElem = xmldoc.createElement("memo");
      theElem.setTextContent("新書的更好看。");
      theBook.appendChild(theElem);
      root.appendChild(theBook);
      System.out.println("--- 新建一本書開始 ----");
      output(xmldoc);
      // --- 新建一本書完成 ----
      // --- 下面對(duì)《哈里波特》做一些修改。 ----
      // --- 查詢找《哈里波特》----
      theBook = (Element) selectSingleNode("/books/book[name='哈里波特']",
          root);
      System.out.println("--- 查詢找《哈里波特》 ----");
      output(theBook);
      // --- 此時(shí)修改這本書的價(jià)格 -----
      theBook.getElementsByTagName("price").item(0).setTextContent("15");// getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當(dāng)于xpath的".//price"。
      System.out.println("--- 此時(shí)修改這本書的價(jià)格 ----");
      output(theBook);
      // --- 另外還想加一個(gè)屬性id,值為B01 ----
      theBook.setAttribute("id", "B01");
      System.out.println("--- 另外還想加一個(gè)屬性id,值為B01 ----");
      output(theBook);
      // --- 對(duì)《哈里波特》修改完成。 ----
      // --- 要用id屬性刪除《三國(guó)演義》這本書 ----
      theBook = (Element) selectSingleNode("/books/book[@id='B02']", root);
      System.out.println("--- 要用id屬性刪除《三國(guó)演義》這本書 ----");
      output(theBook);
      theBook.getParentNode().removeChild(theBook);
      System.out.println("--- 刪除后的XML ----");
      output(xmldoc);
      // --- 再將所有價(jià)格低于10的書刪除 ----
      NodeList someBooks = selectNodes("/books/book[price<10]", root);
      System.out.println("--- 再將所有價(jià)格低于10的書刪除 ---");
      System.out.println("--- 符合條件的書有 " + someBooks.getLength()
          + "本。 ---");
      for (int i = 0; i < someBooks.getLength(); i++) {
        someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
      }
      output(xmldoc);
      saveXml("Test1_Edited.xml", xmldoc);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * 將node的XML字符串輸出到控制臺(tái)
   *
   * @param node
   */
  public static void output(Node node) {
    TransformerFactory transFactory = TransformerFactory.newInstance();
    try {
      Transformer transformer = transFactory.newTransformer();
      transformer.setOutputProperty("encoding", "gb2312");
      transformer.setOutputProperty("indent", "yes");
      DOMSource source = new DOMSource();
      source.setNode(node);
      StreamResult result = new StreamResult();
      result.setOutputStream(System.out);
      transformer.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * 查找節(jié)點(diǎn),并返回第一個(gè)符合條件節(jié)點(diǎn)
   *
   * @param express
   * @param source
   * @return
   */
  public static Node selectSingleNode(String express, Object source) {
    Node result = null;
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    try {
      result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
    return result;
  }
  /**
   * 查找節(jié)點(diǎn),返回符合條件的節(jié)點(diǎn)集。
   * @param express
   * @param source
   * @return
   */
  public static NodeList selectNodes(String express, Object source) {
    NodeList result = null;
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    try {
      result = (NodeList) xpath.evaluate(express, source,
          XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
    return result;
  }
  /**
   * 將Document輸出到文件
   * @param fileName
   * @param doc
   */
  public static void saveXml(String fileName, Document doc) {
    TransformerFactory transFactory = TransformerFactory.newInstance();
    try {
      Transformer transformer = transFactory.newTransformer();
      transformer.setOutputProperty("indent", "yes");
      DOMSource source = new DOMSource();
      source.setNode(doc);
      StreamResult result = new StreamResult();
      result.setOutputStream(new FileOutputStream(fileName));
      transformer.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:

在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson

在線格式化XML/在線壓縮XML
http://tools.jb51.net/code/xmlformat

XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • JAVA IO的3種類型區(qū)別解析

    JAVA IO的3種類型區(qū)別解析

    這篇文章主要介紹了JAVA IO的3種類型解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Java設(shè)計(jì)模式之java狀態(tài)模式詳解

    Java設(shè)計(jì)模式之java狀態(tài)模式詳解

    這篇文章主要介紹了Java設(shè)計(jì)模式之狀態(tài)模式定義與用法,結(jié)合具體實(shí)例形式詳細(xì)分析了Java狀態(tài)模式的概念、原理、定義及相關(guān)操作技巧,需要的朋友可以參考下
    2021-09-09
  • Spring?Boot?Aop執(zhí)行順序深入探究

    Spring?Boot?Aop執(zhí)行順序深入探究

    這篇文章主要為大家介紹了Spring?Boot?Aop執(zhí)行順序深入探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Spring Boot日志的打印與持久化詳細(xì)解析

    Spring Boot日志的打印與持久化詳細(xì)解析

    Spring Boot默認(rèn)使用SLF4J+Logback 記錄日志,并提供了默認(rèn)配置,即使我們不進(jìn)行任何額外配,也可以使用SLF4J+Logback進(jìn)行日志輸出
    2022-07-07
  • Java 十大排序算法之希爾排序刨析

    Java 十大排序算法之希爾排序刨析

    希爾排序是希爾(Donald Shell)于1959年提出的一種排序算法。希爾排序也是一種插入排序,它是簡(jiǎn)單插入排序經(jīng)過(guò)改進(jìn)之后的一個(gè)更高效的版本,也稱為縮小增量排序,同時(shí)該算法是沖破O(n2)的第一批算法之一。本文會(huì)以圖解的方式詳細(xì)介紹希爾排序的基本思想及其代碼實(shí)現(xiàn)
    2021-11-11
  • Java各種鎖在工作中使用場(chǎng)景和細(xì)節(jié)經(jīng)驗(yàn)總結(jié)

    Java各種鎖在工作中使用場(chǎng)景和細(xì)節(jié)經(jīng)驗(yàn)總結(jié)

    本章主要說(shuō)一說(shuō)鎖在工作中的使用場(chǎng)景,主要以 synchronized 和 CountDownLatch 為例,會(huì)分別描述一下這兩種鎖的使用場(chǎng)景和姿勢(shì)
    2022-03-03
  • SpringBoot2.6.x升級(jí)后循環(huán)依賴及Swagger無(wú)法使用問(wèn)題

    SpringBoot2.6.x升級(jí)后循環(huán)依賴及Swagger無(wú)法使用問(wèn)題

    這篇文章主要為大家介紹了SpringBoot2.6.x升級(jí)后循環(huán)依賴及Swagger無(wú)法使用問(wèn)題,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • 淺談Java注解和動(dòng)態(tài)代理

    淺談Java注解和動(dòng)態(tài)代理

    這篇文章主要介紹了Java中有關(guān)注解和動(dòng)態(tài)代理的一些知識(shí),涉及了Annotation、數(shù)據(jù)類型等相關(guān)內(nèi)容,需要的朋友可以參考下。
    2017-09-09
  • SpringBoot 如何優(yōu)雅的實(shí)現(xiàn)跨服務(wù)器上傳文件的示例

    SpringBoot 如何優(yōu)雅的實(shí)現(xiàn)跨服務(wù)器上傳文件的示例

    這篇文章主要介紹了SpringBoot 如何優(yōu)雅的實(shí)現(xiàn)跨服務(wù)器上傳文件的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2006-11-11
  • Java源碼解析CopyOnWriteArrayList的講解

    Java源碼解析CopyOnWriteArrayList的講解

    今天小編就為大家分享一篇關(guān)于Java源碼解析CopyOnWriteArrayList的講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01

最新評(píng)論