Java对XML文件增删改查操作示例

小编 2026-06-17 阅读:965 评论:0
本文实例讲述了Java对XML文件增删改查操作。分享给大家供大家参考,具体如下: xml文件: <?xml version=\"1.0\" encoding=\"UTF-8\"?...

本文实例讲述了Java对XML文件增删改查操作。分享给大家供大家参考,具体如下:

xml文件:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<books>
  <book>
    <name>哈里波特</name>
    <price>10</price>
    <memo>这是一本很好看的书。</memo>
  </book>
  <book id=\"B02\">
    <name>三国演义</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);
      // --- 新建一本书完成 ----
      // --- 下面对《哈里波特》做一些修改。 ----
      // --- 查询找《哈里波特》----
      theBook = (Element) selectSingleNode(\"/books/book[name=\'哈里波特\']\",
          root);
      System.out.println(\"--- 查询找《哈里波特》 ----\");
      output(theBook);
      // --- 此时修改这本书的价格 -----
      theBook.getElementsByTagName(\"price\").item(0).setTextContent(\"15\");// getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName(\"price\")相当于xpath的\".//price\"。
      System.out.println(\"--- 此时修改这本书的价格 ----\");
      output(theBook);
      // --- 另外还想加一个属性id,值为B01 ----
      theBook.setAttribute(\"id\", \"B01\");
      System.out.println(\"--- 另外还想加一个属性id,值为B01 ----\");
      output(theBook);
      // --- 对《哈里波特》修改完成。 ----
      // --- 要用id属性删除《三国演义》这本书 ----
      theBook = (Element) selectSingleNode(\"/books/book[@id=\'B02\']\", root);
      System.out.println(\"--- 要用id属性删除《三国演义》这本书 ----\");
      output(theBook);
      theBook.getParentNode().removeChild(theBook);
      System.out.println(\"--- 删除后的XML ----\");
      output(xmldoc);
      // --- 再将所有价格低于10的书删除 ----
      NodeList someBooks = selectNodes(\"/books/book[price<10]\", root);
      System.out.println(\"--- 再将所有价格低于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字符串输出到控制台
   *
   * @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();
    }
  }
  /**
   * 查找节点,并返回第一个符合条件节点
   *
   * @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;
  }
  /**
   * 查找节点,返回符合条件的节点集。
   * @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:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
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

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
标签列表