JAVA對XML的添、刪、改、查操作

來源:互聯網
上載者:User

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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.