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>

java对xml文件做增删改查------摘录的更多相关文章

  1. java对xml文件做增删改查

    http://www.cnblogs.com/wangchenyang/archive/2011/08/23/2150530.html http://www.blogjava.net/weishuan ...

  2. Java使用DOM4J对XML文件进行增删改查操作

    Java进行XML文件操作,代码如下: package com.founder.mrp.util; import java.io.File; import java.util.ArrayList; i ...

  3. 使用dom4j对xml文件进行增删改查

    1.使用dom4j技术对dom_demo.xml进行增删改查 首选要下载dom4j的jar包 在官网上找不到,网上搜索了一下在这个链接:http://sourceforge.net/projects/ ...

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

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

  5. php对xml文件的增删改查

    源文件<?xml version="1.0" encoding="utf-8"?><root>  <endTime>2016 ...

  6. C# 本地xml文件进行增删改查

    项目添加XML文件:FaceXml.xml,并复制到输出目录 FaceXml.xml <?xml version="1.0" encoding="utf-8&quo ...

  7. xml 文件的增删改查

    序列化和反序列化helper using System; using System.Collections.Generic; using System.Linq; using System.Text; ...

  8. MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存

    目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...

  9. MyBatis学习(二)、SQL语句映射文件(2)增删改查、参数、缓存

    二.SQL语句映射文件(2)增删改查.参数.缓存 2.2 select 一个select 元素非常简单.例如: <!-- 查询学生,根据id --> <select id=" ...

随机推荐

  1. javascript URI的编码

    用encodeURIComponent,但是不清楚她和encodeURI的区别, w3school 对其的解释: encodeURIComponent() 函数可把字符串作为 URI 组件进行编码.( ...

  2. django(五)

    URLs 当一个用户请求一个页面时,Django将按照顺序去匹配每一个模式,并停在第一个匹配请求的URL上. 如果你的url多个正则表达式都能匹配上咋弄?小心出错,这个是按照顺序匹配的 url(r'^ ...

  3. jQuery实现抖动效果

    //抖动效果 //intShakes:抖动次数:intDistance:抖动左右距离:intDuration:持续时间 jQuery.fn.shake = function (intShakes, i ...

  4. Linux 命令 ls -l

    一.ll命令 ll并不是linux下一个基本的命令,它实际上是ls -l的一个别名. Ubuntu默认不支持命令ll,必须用 ls -l,这样使用起来不是很方便. 如果要使用此命令,可以作如下修改:打 ...

  5. Http的请求对象

    Servlet 客户端 HTTP 请求 当浏览器请求网页时,它会向 Web 服务器发送特定信息,这些信息不能被直接读取,因为这些信息是作为 HTTP 请求的头的一部分进行传输的.您可以查看 HTTP ...

  6. vim总结

    1.vim基础用法 注:该思维导图来自笔者<Linux就该这么学>读书笔记. 移动光标: 命令 描述 k 向上移动光标(移动一行) j 向下移动光标(移动一行) h 向左移动光标(移动一个 ...

  7. WebService到底是什么?

    一.序言 大家或多或少都听过WebService(Web服务),有一段时间很多计算机期刊.书籍和网站都大肆的提及和宣传WebService技术,其中不乏很多吹嘘和做广告的成分.但是不得不承认的是Web ...

  8. jqeury 合并单元格

    function mergeCells() { var tbodyTlth = $("#datatable_ajax1 tbody").find("tr").l ...

  9. HTML标签CSS默认值研究

    最近写css的时候,发现在div元素里面添加ul元素后发现,ul列表在div里面距离最上方总是有一段空行,当时很奇怪,以为是哪个css出了问题,就把css去掉了,发现问题依旧,然后就查了一下发现htm ...

  10. 【微博SDK调用逻辑】微博SDK的调用逻辑,最好自己还是写一个例子,试一下!!!

    逻辑是这样的,谢谢给我讲东西的开发哥哥,嘻嘻~~~  1.点击微博登录,SDK会打开微博客户端,然后点击登陆(如果已经登录了会出现一个当前app跟微博交互的图片界面,然后提示“正在获取授权信息”,如果 ...