zoukankan      html  css  js  c++  java
  • JAVA对XML的添、删、改、查操作

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;

    import org.w3c.dom.*;
    import org.xml.sax.SAXException;

    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 testXmlRoles {
     
     public static void main(String[] args) {
      if(args.length>0){   
       String method = args[0];
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       //根节点
       Element root = null;
       //子节点
       Element theRole = null;
       //子节点元素
       Element theElem = null;
       try {
        factory.setIgnoringElementContentWhitespace(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document xmldoc = db.parse(new File("Test.xml"));
        root = xmldoc.getDocumentElement();
                 //--- 新建一角色(子节点) ----
           //调用格式 :java TestXmlRoles add newrole 12 123456
        if(method.equals("add")){
          if(args.length!=4){
           System.out.println("请输入四个参数:格式例如-->java TestXmlRoles add newrole 12 123456"); 
          }else{
           theRole = (Element) selectSingleNode("/roles/role[name='" + args[1] + "' and id='"+args[2]+"']", root);
           if(theRole!=null){
            System.out.println("---该name或者id已经存在,请另设----");
           }else{
            theRole = xmldoc.createElement("role"); 
            //附加子节点元素   
            theElem = xmldoc.createElement("name");
            theElem.setTextContent(args[1]);   
            theRole.appendChild(theElem);
            
            theElem = xmldoc.createElement("id");
            theElem.setTextContent(args[2]);
            theRole.appendChild(theElem);
            
            theElem = xmldoc.createElement("pas");
            theElem.setTextContent(args[3]);
            theRole.appendChild(theElem);
            //根节点附加子节点
            root.appendChild(theRole);   
            output(xmldoc);
            saveXml("Test.xml", xmldoc);
            System.out.println("---添加成功----");
           }       
          }      
         }
         
       //--- 要用id属性删除角色 ----
       //调用格式 :java TestXmlRoles delbyid 12
         else if (method.equals("delbyid")) {
         if (args.length != 2) {
          System.out.println("请输入id:格式例如-->java TestXmlRoles delbyid 12");
         } else {
          theRole = (Element) selectSingleNode("/roles/role[id='"+ args[1] + "']", root);
          if (theRole != null) {
           theRole.getParentNode().removeChild(theRole);
           saveXml("Test.xml", xmldoc);
           System.out.println("---删除成功----");
          } else {
           System.out.println("--不存在该id的角色 ----");
          }

         }
        }
         
               //--- 要用name属性删除角色 ----
         //调用格式 :java TestXmlRoles delbyname newrole
          else if (method.equals("delbyname")) {
         if (args.length != 2) {
          System.out.println("请输入name参数:格式例如-->java TestXmlRoles delbyname newrole");
         } else {
          theRole = (Element) selectSingleNode("/roles/role[name='" + args[1] + "']", root);
          if (theRole != null) {
           theRole.getParentNode().removeChild(theRole);
           saveXml("Test.xml", xmldoc);
           System.out.println("---删除成功----");
          } else {
           System.out.println("---不存在名称对应的角色----");
          }
         }
        }
         
         //根据name查找id,pas
         //调用格式 java TestXmlRoles findbyname newrole
         else if (method.equals("findbyname")) {
         if (args.length != 2) {
          System.out.println("请输入name参数:格式例如-->java TestXmlRoles findbyname newrole");
         } else {
          theRole = (Element) selectSingleNode("/roles/role[name='" + args[1] + "']", root);
          if (theRole != null) {
           // getElementsByTagName返回的是NodeList,所以要跟上item(0)
           String password = theRole.getElementsByTagName("pas").item(0).getTextContent();
           String id = theRole.getElementsByTagName("id").item(0).getTextContent();
           System.out.println("---  对应角色id 和密码:----" + id+ "," + password);
          } else {
           System.out.println("---不存在该名称的角色---");
          }
         }
        }
         
                     // 根据id查找name,pas
        // 调用格式 java TestXmlRoles findbyid 30
        else if (method.equals("findbyid")) {
         if (args.length != 2) {
          System.out.println("请输入id参数:格式例如-->java TestXmlRoles findbyid 30");
         } else {
          theRole = (Element) selectSingleNode("/roles/role[id='"+ args[1] + "']", root);
          if(theRole!=null){
                                //getElementsByTagName返回的是NodeList,所以要跟上item(0)
           String password = theRole.getElementsByTagName("pas").item(0).getTextContent();
           String name = theRole.getElementsByTagName("name").item(0).getTextContent();
           System.out.println("---  对应角色id 和密码:----" + name + ","+ password);
          }else{
           System.out.println("---没有找到相关记录---");
          }      
         }
        }
         
         // --- 根据name对role做一些修改。 ----
         //调用格式 java TestXmlRoles editbyname cs 8888888
        else if(method.equals("editbyname")){
           if(args.length!=2){
          System.out.println("请输入name参数:格式例如-->java TestXmlRoles editbyname cs 8888888"); 
           }else{
          theRole = (Element) selectSingleNode("/roles/role[name='"+args[1]+"']",root);
                            if(theRole!=null){
                                //--- 修改角色密码 -----
                             //getElementsByTagName返回的是NodeList,所以要跟上item(0)
              theRole.getElementsByTagName("pas").item(0).setTextContent(args[2]);
              /*// --- 给节点加一个属性'id',值为B01 ----
              theRole.setAttribute("id", "B01");
              output(theRole);*/
              saveXml("Test.xml", xmldoc);
          }else{
           System.out.println("---没有找到相关记录---");
          }      
          }
            }
         
         //批量删除
         //调用格式 java TestXmlRoles delbanch id<10
        else if(method.equals("delbanch")){
          if(args.length!=2){
          System.out.println("请输入删除条件:格式例如-->java TestXmlRoles delbanch id<10"); 
          }else{
                         //NodeList someRoles = selectNodes("/roles/role[id<10]", root);
          NodeList someRoles = selectNodes("/roles/role["+args[2]+"]", root);
          System.out.println("---  符合条件的角色有 " + someRoles.getLength()+ "个 ---");
          for (int i = 0; i < someRoles.getLength(); i++) {
           someRoles.item(i).getParentNode().removeChild(someRoles.item(i));
          }
          saveXml("Test.xml", xmldoc);
          }
          }else{
                     System.out.println("--- 请输入正确的方法名称---");
          }
       } catch (ParserConfigurationException e) {
        e.printStackTrace();
       } catch (SAXException e) {
        e.printStackTrace();
       } catch (IOException e) {
        e.printStackTrace();
       }
      } else {
       System.out.println("调用该程序需要输入相关参数:格式例如-->java TestXmlRoles add newrole 12 123456");
      }  
     }

    //  将node的XML字符串输出到控制台
     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 (TransformerConfigurationException e) {
       e.printStackTrace();
      } catch (TransformerException e) {
       e.printStackTrace();
      }
     }

    //  查找节点,并返回第一个符合条件节点
     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;
     }

    //  查找节点,返回符合条件的节点集。
     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输出到文件
     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 (TransformerConfigurationException e) {
       e.printStackTrace();
      } catch (TransformerException e) {
       e.printStackTrace();
      } catch (FileNotFoundException e) {
       e.printStackTrace();
      }
     }
    }

    XML文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <roles>
     <role>
      <name>张三</name>
      <id>10</id>
      <pas>789456</pas>
     </role>
     <role>
      <name>李四</name>
      <id>20</id>
      <pas>654321</pas>
     </role>
      
       
    <role id="B01">
    <name>cs</name>
    <id>30</id>
    <pas>8888888</pas>
    </role>


    </roles>

  • 相关阅读:
    Id vs Instancetype
    【转】为什么要走出你的心理“舒适区”
    【转】深入浅出 iOS 之生命周期
    【转】Objective-C类初始化:load与initialize
    【转】Cocoapod 的安装和使用
    非对称加密回顾
    iOS中 Proxy和的delegate区别
    IOS 对JSON解析的要求
    内存对齐规则
    KVO 的进一步理解
  • 原文地址:https://www.cnblogs.com/willpower/p/1204099.html
Copyright © 2011-2022 走看看