java对xml文件做增删改查

package com.wss;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

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 org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class GPS_GNSS_XML_Color {
    //删除节点时传入的参数
    private static String deleteNumber;
    
    //修改节点时传入的参数
    private static String updateNumber;
    
    //读取传入的路径,返回一个document对象
    public static Document loadInit(String filePath){
        Document document = null;
        try{
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(new File(filePath));
            document.normalize();
            return document;
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        }
    }

/**
     * 删除制定的xml
     * @param filePath
     * @return
     */
    public static boolean deleteXML(String filePath){
        deleteNumber = "421f481e-790c-41be-91e3-27d215b73ce2";
        Document document = loadInit(filePath);
        try{
            NodeList nodeList = document.getElementsByTagName("color");
            for(int i=0; i<nodeList.getLength(); i++){
                String number_ = document.getElementsByTagName("number").item(i).getFirstChild().getNodeValue();
                //删除节点时传入的参数
                if(number_.equals(deleteNumber)){
                    Node node = nodeList.item(i);
                    node.getParentNode().removeChild(node);
                    saveXML(document, filePath);
                }
            }
            return true;
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            return false;
        }
    }
    
    /**
     * 修改制定的xml
     * @param filePath
     * @return
     */
    public static boolean updateXML(String filePath){
        updateNumber = "421f481e-790c-41be-91e3-27d215b73ce2";
         //读取传入的路径,返回一个document对象
         Document document = loadInit(filePath);
         try{
            //获取叶节点
             NodeList nodeList = document.getElementsByTagName("color");
            //遍历叶节点
             for(int i=0; i<nodeList.getLength(); i++){
                 String number = document.getElementsByTagName("number").item(i).getFirstChild().getNodeValue();
                 String colorValue = document.getElementsByTagName("colorValue").item(i).getFirstChild().getNodeValue();
                 Double minValue = Double.parseDouble(document.getElementsByTagName("minValue").item(i).getFirstChild().getNodeValue());
                 Double maxValue = Double.parseDouble(document.getElementsByTagName("maxValue").item(i).getFirstChild().getNodeValue());
                 //修改节点时传入的参数
                 if(number.equals(updateNumber)){
                     document.getElementsByTagName("colorValue").item(i).getFirstChild().setNodeValue("black");
                     document.getElementsByTagName("minValue").item(i).getFirstChild().setNodeValue("2222");
                     document.getElementsByTagName("maxValue").item(i).getFirstChild().setNodeValue("22222");
                     System.out.println();
                 }
             }
             saveXML(document, filePath);
             return true;
         }catch(Exception e){
             e.printStackTrace();
             System.out.println(e.getMessage());
             return false;
         }
    }
    
    /**
     * 添加节点
     * @param filePath
     * @return
     */
    public static boolean addXML(String filePath){
        try{
            //读取传入的路径,返回一个document对象
            Document document = loadInit(filePath);
            //创建叶节点
            Element eltColor = document.createElement("color");
            Element eltNumber = document.createElement("number");//创建叶节点的第一个元素
            Element eltColorValue = document.createElement("colorValue");//创建叶节点的第二个元素
            Element eltMinValue = document.createElement("minValue");//创建叶节点的第三个元素
            Element eltMaxValue = document.createElement("maxValue");//创建叶节点的第四个元素
            Text number_ = document.createTextNode(UUID.randomUUID().toString());//创建叶节点的第一个元素下的文本节点
            eltNumber.appendChild(number_);//把该文本节点加入到叶节点的第一个元素里面
            Text colorValue_ = document.createTextNode("colorValue");//创建叶节点的第二个元素下的文本节点
            eltColorValue.appendChild(colorValue_);//把该文本节点加入到叶节点的第二个元素里面
            Text minValue_ = document.createTextNode("100");//创建叶节点的第三个元素下的文本节点
            eltMinValue.appendChild(minValue_);//把该文本节点加入到叶节点的第三个元素里面
            Text maxValue_ = document.createTextNode("200");//创建叶节点的第四个元素下的文本节点
            eltMaxValue.appendChild(maxValue_);//把该文本节点加入到叶节点的第四个元素里面
            //把叶节点下的元素加入到叶节点下
            eltColor.appendChild(eltNumber);
            eltColor.appendChild(eltColorValue);
            eltColor.appendChild(eltMinValue);
            eltColor.appendChild(eltMaxValue);
            //获取根节点
            Element eltRoot = document.getDocumentElement();
            //把叶节点加入到根节点下
            eltRoot.appendChild(eltColor);
            //更新修改后的源文件
            saveXML(document, filePath);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            return false;
        }
    }
    
    /**
     * 把修改后的document写进源文件(更新源文件)
     * @param document
     * @param filePath
     * @return
     */
    public static boolean saveXML(Document document, String filePath){
        try{
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new File(filePath));
            transformer.transform(source, result);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取xml文件的所有记录
     * @param filePath
     * @return
     */
    public static List<ColorValue> selectXML(String filePath){
         List<ColorValue> colorValueList = new ArrayList<ColorValue>();
         try{
             //读取传入的路径,返回一个document对象
             Document document = loadInit(filePath);
             //获取叶节点
             NodeList nodeList = document.getElementsByTagName("color");
             //遍历叶节点
             for(int i=0; i<nodeList.getLength(); i++){
                 ColorValue colorValue = new ColorValue();
                 String number_ = document.getElementsByTagName("number").item(i).getFirstChild().getNodeValue();
                 String colorValue_ = document.getElementsByTagName("colorValue").item(i).getFirstChild().getNodeValue();
                 Double minValue_ = Double.parseDouble(document.getElementsByTagName("minValue").item(i).getFirstChild().getNodeValue());
                 Double maxValue_ = Double.parseDouble(document.getElementsByTagName("maxValue").item(i).getFirstChild().getNodeValue());
                 colorValue.setNumber(number_);
                 colorValue.setColorValue(colorValue_);
                 colorValue.setMinValue(minValue_);
                 colorValue.setMaxValue(maxValue_);
                 colorValueList.add(colorValue);
             }
             return colorValueList;
         }catch(Exception e){
             e.printStackTrace();
             System.out.println(e.getMessage());
             return null;
         }
    }
}

package com.wss;

public class ColorValue {

private String number;
    private String colorValue;
    private Double minValue;
    private Double maxValue;
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public String getColorValue() {
        return colorValue;
    }
    public void setColorValue(String colorValue) {
        this.colorValue = colorValue;
    }
    public Double getMinValue() {
        return minValue;
    }
    public void setMinValue(Double minValue) {
        this.minValue = minValue;
    }
    public Double getMaxValue() {
        return maxValue;
    }
    public void setMaxValue(Double maxValue) {
        this.maxValue = maxValue;
    }
}

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Colors>
    <color>
        <number>7007b384-fab3-4779-9171-229d0664b6b5</number>
        <colorValue>black</colorValue>
        <minValue>2222</minValue>
        <maxValue>22222</maxValue>
    </color>
    <color>
        <number>421f481e-790c-41be-91e3-27d215b73ce2</number>
        <colorValue>colorValue</colorValue>
        <minValue>100</minValue>
        <maxValue>200</maxValue>
    </color>
</Colors>

转载于:https://www.cnblogs.com/ximencuixue/p/3200471.html

java对xml文件做增删改查------摘录相关推荐

  1. Java程序员除了做增删改查还能干嘛?

    就以Java后端开发为例,说说不同级别程序员干的事情. 1 初级开发,大概是有3年Java开发经验. 22年底,上海,这批程序员如果学历是本科,薪资一般是8k到2w,当然如果能进好公司或互联网大厂,薪 ...

  2. dom4j创建、解析xml文件(增删改查)

    先对xml文件进行解析,xml文件如下图所示 <?xml version="1.0" encoding="UTF-8"?> <?eclipse ...

  3. 对xml文件的增删改查及读写

    示例1 1.xml 是QT 另外需要手动添加的模块. 在pro 文件中需要手动添加: QT += xml 2.xml头文件需要用到#include<QtXml> , 当然这是包含了xml ...

  4. Asp.Net 操作XML文件的增删改查 利用GridView

    不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...

  5. [PYTHON] 对XML文件进行增删改查操作

    PYTHON 操作 XML 读取XML文件 关于XML的介绍 <data> 与 </data> 是一对标签的开始与结束 <property - /> 也是一个正确的 ...

  6. Java实现对文件的增删改查操作

    1.建立一个文件存放数据 2.首先创建一个person类,声明姓名,年龄. 下面展示一些 内联代码片. class Person {String name;int age;public String ...

  7. Mybatis入门:2(xml形式的增删改查)

    xml形式的增删改查 这里感觉没啥好讲的,照着代码自己敲一遍.认真再看看应该都懂的. Maven工程坐标 <?xml version="1.0" encoding=" ...

  8. 我在外包公司做增删改查有前途么?

    作者:邹溪源,长沙资深互联网从业者,架构师社区特邀嘉宾! 起因 这是我无意中在筛选简历时,看到一位朋友发布的求职说明中,明确指出,外包勿扰,并给出了他做出这个决定的理由: 过去若干年间,他一直在中软国 ...

  9. 使用dbutils对mysql数据库做增删改查的基本操作方法

    2019独角兽企业重金招聘Python工程师标准>>> 1.数据库名:phoenix_uml,t_user.sql 表结构 SET FOREIGN_KEY_CHECKS=0;-- - ...

最新文章

  1. 解决windows7下vs2008不能正常编译ActiveX控件的问题
  2. 构建之法读书笔记之五
  3. 5G时代到来,SD-WAN如何发展?-Vecloud微云
  4. 安装zabbix4.0+grafana
  5. 阿里公共DNS正式发布:223.5.5.5 223.6.6.6
  6. Servlet 文件上传
  7. 收起虚拟键盘的各种方法 -- IOS
  8. # 取字典的值_python3的列表、元组、字典的复习和推导式和生成器小结
  9. 3299元!最便宜的5G手机明日开启预售
  10. 关于js弹出框的介绍:
  11. Java SE 随机数生成器 Random
  12. _wsplitpath_s
  13. js判断传入时间和当前时间大小
  14. vue高德地图H5定位及城市选择器控件实现详细教程
  15. JDK下载安装教程及环境变量配置
  16. 免费下载微软原厂Win11镜像ISO文件
  17. OSPF协议的四种网络类型
  18. ue4 vr连接_基于UE4的VR项目基础环境配置和Motion Controller控制配置
  19. Ledger Nano X初始化使用教程
  20. uni-app开发app之一uni-app优缺点

热门文章

  1. redis List的用途及常用命令
  2. Lua 脚本获取 EVAL EVALSHA 命令的参数
  3. 信号与线性系统分析_什么是线性系统?如何辨别控制系统?控制系统基本要求是什么?...
  4. php点菜系统开题报告,点餐管理系统的设计与实现-开题报告
  5. 系统 CPU 突然飙升且 GC 频繁,如何排查
  6. C++ warning:’xxx‘ has no out-of-line virtual method definitions...
  7. Python常用技巧了解一下?
  8. 极客时间《玩转Git三剑客》之GItHub剑客
  9. python 3.8.2 / 内置的数据结构 / list (类似于 STL 中的 vector)
  10. linux socket API / bind