java使用DOM對XML文檔進行增刪改查操作執行個體代碼,domxml

來源:互聯網
上載者:User

java使用DOM對XML文檔進行增刪改查操作執行個體代碼,domxml

本文研究的主要是java使用DOM對XML文檔進行增刪改查操作的相關代碼,具體執行個體如下所示。

原始碼:

package com.zc.homeWork18;import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathExpressionException;import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class XMLWriter {  private static String xmlPath = "src\\com\\zc\\homeWork18\\MyXml.xml";  public static void getFamilyMemebers() {  /*     * 建立檔案工廠執行個體     */    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    // 如果建立的解析器在解析XML文檔時必須刪除元素內容中的空格,則為true,否則為false    dbf.setIgnoringElementContentWhitespace(true);    try {      /*       * 建立檔案對象       */      DocumentBuilder db = dbf.newDocumentBuilder();// 建立解析器,解析XML文檔      Document doc = db.parse(xmlPath); // 使用dom解析xml檔案      /*       * 曆遍列表,進行XML檔案的資料提取       */      // 根據節點名稱來擷取所有相關的節點      NodeList sonlist = doc.getElementsByTagName("son");      for (int i = 0; i < sonlist.getLength(); i++) // 迴圈處理對象      {        // 節點屬性的處理        Element son = (Element) sonlist.item(i);        // 迴圈節點son內的所有子節點        for (Node node = son.getFirstChild(); node != null; node = node            .getNextSibling()) {          // 判斷是否為元素節點          if (node.getNodeType() == Node.ELEMENT_NODE) {            String name = node.getNodeName();            String value = node.getFirstChild().getNodeValue();            System.out.println(name + " : " + value);          }        }      }    } catch (Exception e) {      System.out.println(e.getMessage());    }  }  // 修改  public static void modifySon() {    // 建立檔案工廠執行個體    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    dbf.setIgnoringElementContentWhitespace(true);    try {      // 從XML文檔中擷取DOM文檔執行個體      DocumentBuilder db = dbf.newDocumentBuilder();      // 擷取Document對象      Document xmldoc = db.parse(xmlPath);      // 擷取根節點      Element root = xmldoc.getDocumentElement();      // 定位id為001的節點      Element per = (Element) selectSingleNode("/father/son[@id='001']",          root);      // 將age節點的內容更改為28      per.getElementsByTagName("age").item(0).setTextContent("28");      // 儲存      TransformerFactory factory = TransformerFactory.newInstance();      Transformer former = factory.newTransformer();      former.transform(new DOMSource(xmldoc), new StreamResult(new File(          xmlPath)));    } catch (Exception e) {      System.out.println(e.getMessage());    }  }  // 擷取目標節點,進行刪除,最後儲存  public static void discardSon() {    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    dbf.setIgnoringElementContentWhitespace(true);    try {      DocumentBuilder db = dbf.newDocumentBuilder();      Document xmldoc = db.parse(xmlPath);      // 擷取根節點      Element root = xmldoc.getDocumentElement();      // 定位根節點中的id=002的節點      Element son = (Element) selectSingleNode("/father/son[@id='002']",          root);      // 刪除該節點      root.removeChild(son);      // 儲存      TransformerFactory factory = TransformerFactory.newInstance();      Transformer former = factory.newTransformer();      former.transform(new DOMSource(xmldoc), new StreamResult(new File(          xmlPath)));    } catch (Exception e) {      System.out.println(e.getMessage());    }  }  // 新增節點  public static void createSon() {    // 建立檔案工廠執行個體    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    dbf.setIgnoringElementContentWhitespace(false);    try {      DocumentBuilder db = dbf.newDocumentBuilder();      // 建立Document對象      Document xmldoc = db.parse(xmlPath);      // 擷取根節點      Element root = xmldoc.getDocumentElement();      // 建立節點son,設定對應的id為004      Element son = xmldoc.createElement("son");      son.setAttribute("id", "004");      // 建立節點name      Element name = xmldoc.createElement("name");      name.setTextContent("小兒子");      son.appendChild(name);      // 建立節點age      Element age = xmldoc.createElement("age");      age.setTextContent("0");      son.appendChild(age);      // 把son添加到根節點中      root.appendChild(son);      // 儲存      TransformerFactory factory = TransformerFactory.newInstance();      Transformer former = factory.newTransformer();      former.transform(new DOMSource(xmldoc), new StreamResult(new File(          xmlPath)));    } catch (Exception e) {      System.out.println(e.getMessage());    }  }  // 修改節點資訊  public static Node selectSingleNode(String express, Element source) {    Node result = null;    //建立XPath工廠    XPathFactory xpathFactory = XPathFactory.newInstance();    //建立XPath對象    XPath xpath = xpathFactory.newXPath();    try {      result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);      System.out.println(result);    } catch (XPathExpressionException e) {      System.out.println(e.getMessage());    }    return result;  }  // 列印  public static void main(String[] args) {    getFamilyMemebers();    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");    modifySon();    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");    System.out.println("修改資料");    getFamilyMemebers();    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");    discardSon();    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");    System.out.println("刪除資料");    getFamilyMemebers();    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");    createSon();    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");    System.out.println("添加資料");    getFamilyMemebers();  }}

XML檔案

<?xml version="1.0" encoding="UTF-8" standalone="no"?><father>  <son id="001">    <name>老大</name>    <age>20</age>  </son>  <son id="002">    <name>老二</name>    <age>18</age>  </son>  <son id="003">    <name>老三</name>    <age>13</age>  </son></father>

總結

以上就是本文關於java使用DOM對XML文檔進行增刪改查操作執行個體代碼的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

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