使用Java怎么对XML文件进行增删改查操作-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

使用Java怎么对XML文件进行增删改查操作

使用Java怎么对XML文件进行增删改查操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

创新互联公司始终坚持【策划先行,效果至上】的经营理念,通过多达十余年累计超上千家客户的网站建设总结了一套系统有效的全网整合营销推广解决方案,现已广泛运用于各行各业的客户,其中包括:成都三维植被网等企业,备受客户称扬。

xml文件:



  
    哈里波特
    10
    这是一本很好看的书。
  
  
    三国演义
    10
    四大名著之一。
  
  
    水浒
    6
    四大名著之一。
  
  
    红楼
    5
    四大名著之一。
  

增删改查 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();
    }
  }
}

关于使用Java怎么对XML文件进行增删改查操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


本文标题:使用Java怎么对XML文件进行增删改查操作
网页地址:http://kswsj.cn/article/gepjsi.html

其他资讯