本文档是我根据自身项目需求对xml的增删改查等方法进行的拓展(下篇)

现在开始对xml进行各种操作,会调用(上篇)写的两个方法

1.添加节点与元素,可以添加一个,或多个,都没关系。网上返回的是boolean值,其实都没关系
 public static void addXML(String filePath){
        try{
            Document document = getDocument(filePath);//获取Document对象

            Element eleColor = document.createElement("color"); //创建子节点
            Element eleNumber = document.createElement("number");//创建子节点的第一个元素
    eleNumber.setAttribute("name","数字");//设置元素的属性,以键值对的形式
     Text number_value= document.createTextNode(UUID.randomUUID().toString());//设置文本节点
           eleNumber.appendChild(number_value);//将文本节点加到该元素下

            Node  rootNode = document.getDocumentElement(); //获取根节点,写Element一样,但写Node更直观
            rootNode.appendChild(eleColor);//把子节点加到根节点下
            saveXML(document, filePath); //更新修改后的源文件
        }catch(Exception e){
            e.printStackTrace();
        }
    }


2.删除其中某一个节点,用的少
 public static void deleteXML(String filePath){
        String  deleteNumber = "421f481e-790c-41be-91e3-27d215b73ce2";//指定要删除的元素的文本值
        Document document = getDocument(filePath);
        try{
            NodeList nodeList = document.getElementsByTagName("color");//得到含有color的子节点数组
            for(int i=0; i<nodeList.getLength(); i++){
                String number_value = document.getElementsByTagName("number").item(i).getFirstChild().getNodeValue();//得到值
                if(number_.equals(deleteNumber)){//相等的情况下
                    Node node = nodeList.item(i);//确定该子节点
                    node.getParentNode().removeChild(node);//从父节点中移除改子节点
                    saveXML(document, filePath);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

3.对xml进行修改(更新)操作,修改一个或多个都可以。
public static void updateXML(String filePath){
        String updateNumber = "421f481e-790c-41be-91e3-27d215b73ce2";
         Document document = getDocument(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(updateNumber)){
                     document.getElementsByTagName("colorValue").item(i).getFirstChild().setNodeValue("hehe");
                 }
             }
             saveXML(document, filePath);
         }catch(Exception e){
             e.printStackTrace();
         }
    }

4.解析xml(查询),与修改查不多,只是将值设置到一个对象中,ColorValue就是自己创建的一个属性类
包含get和set方法,太简单了,就不写了
public static List<ColorValue> selectXML(String filePath){
         List<ColorValue> colorValueList = new ArrayList<ColorValue>();
         try{
             Document document = getDocument(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){
             return null;
         }
    }

5.添加节点到指定的节点下
public static void addNodeToTarget(String filePath){
    try{
        Document document = getDocument(filePath);
        Node root = document.getDocumentElement();
        NodeList childs = root.getChildNodes();//获得根节点下的子节点
        Node newnode = document.createElement("element1");//
        newnode.appendChild(document.createTextNode("abc"));//添加文本值
        Node secondnode = childs.item(1);//获得根节点下的第二个子节点
        root.insertBefore(newnode, secondnode); //把新节点添加到原第二个结点之前
        root.appendChild(newnode);
        saveXML(document, filePath);
    }catch(Exception e){
        e.printStackTrace();
    }
    }

6.这个是我项目需要我自己写的一个添加子节点方法,通过注释就可以明白需求
public static void addXmlBySelf(String filePath){
    try{
        Document document = getDocument(filePath);
        Element root = document.getDocumentElement(); //获得根元素
        NodeList childs = root.getChildNodes();//获得根元素下的所有子节点
        for (int i = 0; i < childs.getLength(); i++) {
        Node node=childs.item(i);//获得其中的一个子节点
        String nodeName=childs.item(i).getNodeName();//得到该子节点的名称
        if(nodeNode.equals("note")){
        int  length=node.getChildNodes().getLength());//得到该子节点下子节点的长度
              Node newnode1 = document.createElement("node1");
            newnode1.appendChild(document.createTextNode("abc"));
            node.appendChild(newnode1);
            root.appendChild(node);
        }
}
        saveXML(document, filePath);
    }catch(Exception e){
        e.printStackTrace();
    }
    }

7.对于我们自己添加的节点,xml不会给我们进行格式化,所以自己写一个格式化的方法
//对xml进行格式化处理,所需要的jar包与xml文件都已上传
public static String format(String xmlPath) {  
try {    
final Document document = getDocument(xmlPath);  
OutputFormat format = new OutputFormat(document);  
format.setLineWidth(65);  
format.setIndenting(true);  
format.setIndent(2);  
Writer out = new StringWriter();  
XMLSerializer serializer = new XMLSerializer(out, format);  
serializer.serialize(document);  
return out.toString(); 
} catch (IOException e) {  
throw new RuntimeException(e);  
}  
}  

//对xml进行格式化处理以后替换掉原来的xml
 public static void replaceFile(String xmlPath, String content) {
    try { 
    FileOutputStream fos = new FileOutputStream(xmlPath); 
    Writer out = new OutputStreamWriter(fos); 
    out.write(content); 
    out.close(); 
    } catch (Exception e) {
    e.printStackTrace();
    }
}

8.写测试方法,只对格式化方法进行测试,其余自己测试
public static void main(String[] args) throws Exception{
String xmlPath="D:/color.xml";
replaceFile(xmlPath, format(xmlPath));  
}  


9.下面是xml文件的内容
<?xml version="1.0" encoding="UTF-8"?>
<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>fdsa</colorValue>
    <minValue>2222.0000</minValue>
    <maxValue>22222.000</maxValue>
  </color>
</Colors>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值