java實現xml文件增刪改查

java一次刪除xml多個節點:

方案1、你直接修改了nodeList,這一般在做循環時是不允許直接這麼做的。你可以嘗試在遍歷一個list時,在循環體同時刪除list裏的內容,你會得到一個異常。建議你如下處理這個問題:
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("11.xml");
            XmlNode root = xmlDoc.DocumentElement;
            XmlNodeList nodeList = root.ChildNodes;

            List<XmlNode> nodesToRemove = new List<XmlNode>();
            foreach (XmlNode node in nodeList)
            {
                if (node.Attributes["FileName"] == null || node.Attributes["FileName"].Value == "")
                {
                    nodesToRemove.Add(node);
                    continue;
                }
                //省略此處代碼dosomething
            }

            foreach (XmlNode node in nodesToRemove)//這裏再來做刪除
            {
                node.ParentNode.RemoveChild(node);
            }

方案2、

 nodelist = xmldoc.SelectSingleNode("employees").ChildNodes;  

while (true)
 2 {
 3     bool removed = false;
 4     foreach (XmlNode xn in nodelist)
 5    {
 6         if (xn.FirstChild.InnerText.ToString().Contains("a"))
 7        {
 8            xn.ParentNode.RemoveChild(xn);
 9            removed = true;
10            break;
11         }
12     }
13 
14     if (!removed)
15          break;
16 }



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;
}
}

public static boolean deleteXML(String filePath){
deleteNumber = "421f481e-790c-41be-91e3-27d215b73ce2";
Document document = loadInit(filePath);
try{
NodeList nodeList = document.getElementsByTagName_r("color");
for(int i=0; i<nodeList.getLength(); i++){
String number_ = document.getElementsByTagName_r("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;
}
}

public static boolean updateXML(String filePath){
updateNumber = "421f481e-790c-41be-91e3-27d215b73ce2";
//讀取傳入的路徑,返回一個document對象
Document document = loadInit(filePath);
try{
//獲取葉節點
NodeList nodeList = document.getElementsByTagName_r("color");
//遍歷葉節點
for(int i=0; i<nodeList.getLength(); i++){
String number = document.getElementsByTagName_r("number").item(i).getFirstChild().getNodeValue();
String colorValue = document.getElementsByTagName_r("colorValue").item(i).getFirstChild().getNodeValue();
Double minValue = Double.parseDouble(document.getElementsByTagName_r("minValue").item(i).getFirstChild().getNodeValue());
Double maxValue =Double.parseDouble(document.getElementsByTagName_r("maxValue").item(i).getFirstChild().getNodeValue());
//修改節點時傳入的參數
if(number.equals(updateNumber)){
document.getElementsByTagName_r("colorValue").item(i).getFirstChild().setNodeValue("black");
document.getElementsByTagName_r("minValue").item(i).getFirstChild().setNodeValue("2222");
document.getElementsByTagName_r("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;
}
}

public static boolean addXML(String filePath){
try{
//讀取傳入的路徑,返回一個document對象
Document document = loadInit(filePath);
//創建葉節點
Element eltColor = document.createElement_x("color");
Element eltNumber = document.createElement_x("number");//創建葉節點的第一個元素
Element eltColorValue = document.createElement_x("colorValue");//創建葉節點的第二個元素
Element eltMinValue = document.createElement_x("minValue");//創建葉節點的第三個元素
Element eltMaxValue = document.createElement_x("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;
}
}

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;
}
}

public static List<ColorValue> selectXML(String filePath){
List<ColorValue> colorValueList = new ArrayList<ColorValue>();
try{
//讀取傳入的路徑,返回一個document對象
Document document = loadInit(filePath);
//獲取葉節點
NodeList nodeList = document.getElementsByTagName_r("color");
//遍歷葉節點
for(int i=0; i<nodeList.getLength(); i++){
ColorValue colorValue = new ColorValue();
String number_ = document.getElementsByTagName_r("number").item(i).getFirstChild().getNodeValue();
String colorValue_ = document.getElementsByTagName_r("colorValue").item(i).getFirstChild().getNodeValue();
Double minValue_ = Double.parseDouble(document.getElementsByTagName_r("minValue").item(i).getFirstChild().getNodeValue());
Double maxValue_ = Double.parseDouble(document.getElementsByTagName_r("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>



xml的初始化及增刪改查操作: 


//初始化 
   private void btnInitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInitActionPerformed 
       // TODO add your handling code here: 
       try { 
           File file = new File("books.xml"); 
           DocumentBuilderFactory docFactory = DocumentBuilderFactory. 
                                               newInstance(); 
           DocumentBuilder builder = docFactory.newDocumentBuilder(); 

           if (!file.exists()) { 
               doc = builder.newDocument(); 
               Element books = doc.createElement("books"); 
               doc.appendChild(books); 
           } else { 
               doc = builder.parse(file); 
           } 
           this.jTextArea1.setText("初始化完成"); 
       } catch (Exception ex) { 
           this.jTextArea1.setText("初始化失敗"); 
       } 
   }//GEN-LAST:event_btnInitActionPerformed 

   private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed 
       // TODO add your handling code here: 
       try { 
           TransformerFactory tfactory = TransformerFactory.newInstance(); 
           Transformer transformer = tfactory.newTransformer(); 
           transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 

           DOMSource source = new DOMSource(doc); 
           StreamResult result = new StreamResult(new File("books.xml")); 

           transformer.transform(source, result); 

           this.jTextArea1.setText("保存成功"); 
       } catch (Exception ex) { 
           this.jTextArea1.setText("保存失敗"); 
       } 
   }//GEN-LAST:event_btnSaveActionPerformed 

   private void btnShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowActionPerformed 
       // TODO add your handling code here: 
       if (doc != null) { 
           Element books = doc.getDocumentElement(); 
           this.jTextArea1.setText(books.getNodeName()); 

           NodeList nl = null; 
           nl = books.getChildNodes(); 
           for (int i = 0; i < nl.getLength(); i++) { 
               Node node = nl.item(i); 
               //節點類型,元素1/屬性2/文本3/註釋8/文檔9 
               if (node.getNodeType() == 1) { 
                   this.jTextArea1.append("\n\t" + node.getNodeName()); 
                   NodeList nsubs = node.getChildNodes(); 
                   for (int j = 0; j < nsubs.getLength(); j++) { 
                       if (nsubs.item(j).getNodeType() == 1 && 
                           nsubs.item(j).getFirstChild() != null) { 
                           this.jTextArea1.append("\n\t\t" + 
                                   nsubs.item(j).getNodeName() + " : " + 
                                   nsubs.item(j).getFirstChild(). 
                                   getNodeValue()); 
                       } 
                   } 
               } 
           } 
       } 
   }//GEN-LAST:event_btnShowActionPerformed 

   private void btnShow2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShow2ActionPerformed 
       // TODO add your handling code here: 
       String msg = ""; 
       if (doc != null){ 
           NodeList nl = doc.getElementsByTagName("*"); 
           
           for (int i=0;i<nl.getLength();i++){ 
               Element e = (Element)nl.item(i); 

               //得到屬性 
               NamedNodeMap nnm = e.getAttributes(); 
               msg += "元素:" + e.getNodeName() +":" + e.getFirstChild().getNodeValue() + "\n"; 

               for (int k=0;k<nnm.getLength();k++){ 
                   Attr att = (Attr)nnm.item(k); 
                   msg += "\t屬性有\t"+ att.getNodeName() + ":" + att.getNodeValue()+"\n"; 
               } 
           } 
       } 
       this.jTextArea1.setText(msg); 
   }//GEN-LAST:event_btnShow2ActionPerformed 

   private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed 
       // TODO add your handling code here: 
       Node node = Search(this.jTextField1.getText()); 
       if (node != null) { 
           this.jTextArea1.setText("找到了此元素"); 
           this.jTextArea1.append("\n\t書籍編號 \t: " + this.jTextField1.getText()); 
           NodeList list = node.getChildNodes(); 
           for (int i = 0; i < list.getLength(); i++) { 
               Node sub = list.item(i); 
               if (sub.getNodeType() == 1 && sub.getFirstChild() != null) { 
                   this.jTextArea1.append("\n\t" + sub.getNodeName() + " \t: " + 
                                          sub.getFirstChild().getNodeValue()); 
               } 
           } 
       } 
       else { 
           this.jTextArea1.setText("找不到此元素"); 
       } 
   }//GEN-LAST:event_btnSearchActionPerformed 

   private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed 
       // TODO add your handling code here: 

       try { 
           //創建元素 
           Element elemBook = doc.createElement("book"); 
           //添加到根元素底下 
           doc.getDocumentElement().appendChild(elemBook); 

           //爲book元素設置屬性 
           Attr attrId = doc.createAttribute("id"); //創建 
           attrId.setNodeValue(this.jTextField1.getText()); //設置值 
           elemBook.setAttributeNode(attrId); //設置到book元素 

           //爲book元素添加子元素name 
           Element elemNode = doc.createElement("name"); //創建 
           Text textNode = doc.createTextNode(this.jTextField2.getText()); //創建文本節點 
           elemNode.appendChild(textNode); //爲name子元素指定文本 
           elemBook.appendChild(elemNode); //添加爲book的子元素 

           //爲book元素添加子元素price 
           elemNode = doc.createElement("price"); //創建 
           textNode = doc.createTextNode(this.jTextField3.getText()); //創建文本節點 
           elemNode.appendChild(textNode); //爲price子元素指定文本 
           elemBook.appendChild(elemNode); //添加爲book的子元素 

           //爲book元素添加子元素pub 
           elemNode = doc.createElement("pub"); //創建 
           textNode = doc.createTextNode(this.jTextField4.getText()); //創建文本節點 
           elemNode.appendChild(textNode); //爲pub子元素指定文本 
           elemBook.appendChild(elemNode); //添加爲book的子元素 

           //爲book元素添加子元素author 
           elemNode = doc.createElement("author"); //創建 
           textNode = doc.createTextNode(this.jTextField5.getText()); //創建文本節點 
           elemNode.appendChild(textNode); //爲author子元素指定文本 
           elemBook.appendChild(elemNode); 

           this.jTextArea1.setText("添加成功"); 
       } catch (Exception ex) { 
           this.jTextArea1.setText("添加失敗"); 
       } 
   }//GEN-LAST:event_btnAddActionPerformed 

   private void btnModifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModifyActionPerformed 
       // TODO add your handling code here: 
       Node node = Search(this.jTextField1.getText()); 
       String[] values = {this.jTextField2.getText(), this.jTextField3.getText(), 
                         this.jTextField4.getText(), this.jTextField5.getText()}; 
       if (node != null) { 
           NodeList nl = node.getChildNodes(); 
           int k = 0; 
           for (int i = 0; i < nl.getLength(); i++) { 
               Node n = nl.item(i); 
               if (n.getNodeType() == 1) { 
                   Node newNode = doc.createTextNode(values[k]); 
                   if (n.getFirstChild() != null) { 
                       n.replaceChild(newNode, n.getFirstChild()); 
                   } else { 
                       n.appendChild(newNode); 
                   } 
                   k = k + 1; 
               } 
           } 
           this.jTextArea1.setText("修改成功"); 
       } else { 
           this.jTextArea1.setText("找不到要修改的節點"); 
       } 
   }//GEN-LAST:event_btnModifyActionPerformed 

   private void btnDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDelActionPerformed 
       // TODO add your handling code here: 
       Node node = Search(this.jTextField1.getText()); 
       if (node != null) { 
           Node parent = node.getParentNode(); 
           parent.removeChild(node); 

           this.jTextArea1.setText("刪除成功"); 
       } else { 
           this.jTextArea1.setText("找不到要刪除的節點"); 
       } 
   }//GEN-LAST:event_btnDelActionPerformed 

   private Node Search(String id) { 
       Node node = null; 
       Element books = doc.getDocumentElement(); 
       NodeList nl = null; 
       if (books.hasChildNodes()) { 
           nl = books.getChildNodes(); 
           for (int i = 0; i < nl.getLength(); i++) { 
               node = nl.item(i); 
               if (node.getNodeType() == 1) { 
                   Element ele = (Element) node; 
                   if (ele.getAttribute("id").equals(id)) { 
                       return node; 
                   } 
               } 
           } 
       } 
       return null; 

   } 


java讀/寫/追加/刪除xml節點  

public class CreateXml { 
  private Document document;
  private String filename;
  DocumentBuilderFactory factory;
  DocumentBuilder builder;  
  public CreateXml(String name){
      filename=name;
      factory=DocumentBuilderFactory.newInstance();
     try {
        builder = factory.newDocumentBuilder();
        document=builder.newDocument();
      } catch (ParserConfigurationException e) {
            e.printStackTrace();
       }     
   }
//寫節點的方法 
 public void toWrite(SystemInfo sBean){
        String sid=String.valueOf(sBean.getId());
        Document doc=null;
        try {
            doc =  builder.parse(new File(filename));
        } catch (SAXException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } 
  //判斷是否有該節點,如果有,則刪除
      NodeList links =doc.getElementsByTagName("System"+sid);  
      if(links.getLength()>0){              //節點已存在
           for (int i=0;i<links.getLength();i++){ 
                 Node nd=links.item(i); 
                 Node catParent = nd.getParentNode();            //得到nd父節點 
                 catParent.removeChild(nd);             //刪除nd節點 
            }
      }
 //寫節點   
          Element system=doc.createElement("System_"+sid);
          Element erefreshCycle=doc.createElement("refreshCycle_"+sid);
          Element esaveInterval=doc.createElement("saveInterval_"+sid);
          Element edataReadCycle=doc.createElement("dataReadCycle_"+sid);
          Element esaveData=doc.createElement("saveData_"+sid);
          Element esoundAlarm=doc.createElement("soundAlarm_"+sid);
  
        Text trefreshCycle=doc.createTextNode(sBean.getRefreshCycle()); 
        Text tsaveInterval=doc.createTextNode(sBean.getSaveInterval()); 
        Text tdataReadCycle=doc.createTextNode(sBean.getDataReadCycle()); 
        Text tsaveData =doc.createTextNode(sBean.getSaveData());
        Text tsoundAlarm=doc.createTextNode(sBean.getSoundAlarm());
        
        Node nrefreshCycle =system.appendChild(erefreshCycle).appendChild(trefreshCycle); 
        Node nsaveInterva = system.appendChild(esaveInterval).appendChild(tsaveInterval); 
        Node ndataReadCycle = system.appendChild(edataReadCycle).appendChild(tdataReadCycle); 
        Node nsaveData = system.appendChild(esaveData).appendChild(tsaveData); 
        Node nsoundAlarm = system.appendChild(esoundAlarm).appendChild(tsoundAlarm); 
        Node nsystem =   doc.getDocumentElement().appendChild(system);

        TransformerFactory   tff   =   TransformerFactory.newInstance(); 
        Transformer tf=null;
         try {
              tf = tff.newTransformer();
              tf.setOutputProperty(OutputKeys.ENCODING,"GB2312");
              tf.setOutputProperty(OutputKeys.INDENT,"yes");
              DOMSource source =new DOMSource(doc); 
              StreamResult rs = new StreamResult(new File(filename)); 
              tf.transform(source,rs); 
         } catch (Exception e) {
             e.printStackTrace();
         } 
     }
}

 

 

//讀xml節點值的方法
public String getPara(String path,String nodeName){
        String node="";
        try
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new File(path));
            Element rootElement = document.getDocumentElement();
            
            NodeList list = rootElement.getElementsByTagName(nodeName);
            if(list.getLength()>0){ 
             Element element = (Element) list.item(0);
             node=element.getChildNodes().item(0).getNodeValue();
            }else{    //沒有配置時,取默認的System_0的內容
             nodeName=nodeName.substring(0,nodeName.indexOf("_"));
             list = rootElement.getElementsByTagName(nodeName+"_0"); 
             Element element = (Element) list.item(0);
             node=element.getChildNodes().item(0).getNodeValue();
            }          
        }
        catch (Exception e)
        {
            System.out.println("exception:" + e.getMessage());
        }
        return node;
    }

 

//調用CreateXML 的方法寫xml節點值:
 String path=request.getSession().getServletContext().getRealPath("/");
 CreateXML xml = new CreateXml(path+"\\system.xml");
 xml.toWrite(systemInfo);             //systemInfo爲一個javaBean

 

system.xml文件內容格式如下:
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<System>
   <System_0>
        <refreshCycle_0>60</refreshCycle_0>
        <saveInterval_0>60</saveInterval_0>
        <dataReadCycle_0>60</dataReadCycle_0>
        <saveData_0>1</saveData_0>
        <soundAlarm_0>1</soundAlarm_0>
   </System_0>
   <System_1>
        <refreshCycle_1>36</refreshCycle_1>
        <saveInterval_1>36</saveInterval_1>
        <dataReadCycle_1>36</dataReadCycle_1>
        <saveData_1>0</saveData_1>
        <soundAlarm_1>1</soundAlarm_1>
   </System_1>
</System>


dom4j xml文檔 增加節點

增加節點

要操作的xml文檔:student.xml

<?xml version="1.0" encoding="gb2312"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<students>
 <student sn="01">
 <name>張三</name>
 <age>18</age>
 </student>
 <student sn="02">
  <name>李四</name>
  <age>20</age>
 </student>
</students>

代碼:

package mydom4j;

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

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class AddNodeTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  SAXReader saxReader=new SAXReader();
  try {
   Document doc=saxReader.read(new File("student.xml"));
   
   Element root=doc.getRootElement();
   //System.out.println(root.getName());
   Element resource=root.addElement("student");
   Element age=resource.addElement("age");
   Element name=resource.addElement("name");
   age.setText("05");
   name.setText("王震");
   OutputFormat opf=new OutputFormat("\t",true,"UTF-8");
   opf.setTrimText(true);
   XMLWriter writer=new XMLWriter(new FileOutputStream("out.xml"),opf);
   writer.write(doc);
   writer.close();
   //System.out.println(root.getName());
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章