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文件CRUD的更多相关文章

  1. # java对xml文件的基本操作

    下面是简单的总结三种常用的java对xml文件的操作 1. dom方式对xml进行操作,这种操作原理是将整个xml文档读入内存总,在内存中进行操作,当xml文档非常庞大的时候就会出现内存溢出的异常,这 ...

  2. 用java操作XML文件(DOM解析方式)

    XML 可扩展标记语言(Extensible Markup Language),是独立于软件和硬件的传输工具. XML的作用: (1)用作配置文件 (2)简化数据共享 (3)简化数据传输 XML DO ...

  3. java对xml文件做增删改查------摘录

    java对xml文件做增删改查 package com.wss; import java.io.File;import java.util.ArrayList;import java.util.Lis ...

  4. 更新java对xml文件的操作

    //更新java在xml文件中操作的内容 public static void upda(Document doc) throws Exception{ //创建一个TransformerFactor ...

  5. Java操作xml文件

    Bbsxml.java public class Bbsxml { private String imgsrc; private String title; private String url; p ...

  6. java 读取XML文件作为配置文件

    首先,贴上自己的实例: XML文件:NewFile.xml(该文件与src目录同级) <?xml version="1.0" encoding="UTF-8&quo ...

  7. java读XML文件

    XML文件设计为传输和存储数据,其焦点为数据内容. HTML设计为用来显示数据, 其焦点为数据外观. XML仅仅是文本文件,任何文本编辑器一般情况下都能对其进行编辑. XML没有预定义的标签,并且设定 ...

  8. java读取xml文件报“org.xml.sax.SAXParseException: Premature end of file” .

    背景:java读取xml文件,xml文件内容只有“<?xml version="1.0" encoding="UTF-8"?>”一行 java读取该 ...

  9. java读取XML文件的四种方式

    java读取XML文件的四种方式 Xml代码 <?xml version="1.0" encoding="GB2312"?> <RESULT& ...

随机推荐

  1. pptv web前端面试题

    今天上午一考完试,就一直等待pptv的电话,结果下午就收到了pptv的通知(pptv的效率还是很不错的,之前面试官和我说在一到两周之内给回复,结果过了7天就给回复了,赞一个)因为我面试的是web前端( ...

  2. ActiveX 暴漏你全部信息的可怕的插件!

    近期在项目中常常接触ActiveX控件,对于这个名词相信仅仅要是上网看视频的用户一定都会遇到adobe更新或者载入的提示,这就是一个ActiveX控件.一直以为Active控件是处理复杂的页面逻辑提供 ...

  3. 设计模式(4)-对象创建型模式-Prototype模式

    1.对象创建型模式 1.4          Protoype模式 1.4.1需求 通过拷贝原形对象创建新的对象. 1.4.2结构 •P r o t o t y p e(Gr a p h i c) - ...

  4. 136 - Ugly Numbers

     Ugly Numbers  Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3 ...

  5. [Android代码阅读]分类简介

    分类简介: 阅读他人的代码,可以学到很多东西,从思路,到方案,一系列都可以在项目代码中体现,所以,此分类专门用于记录阅读过的项目代码,并在上面给出自己的理解和注释 在此,感谢原作者开源分享项目代码

  6. H2O是开源基于大数据的机器学习库包

    H2O是开源基于大数据的机器学习库包 H2O能够让Hadoop做数学,H2O是基于大数据的 统计分析 机器学习和数学库包,让用户基于核心的数学积木搭建应用块代码,采取类似R语言 Excel或JSON等 ...

  7. 利用json获取天气信息

    天气预报信息获取是利用json获取的,网上有非常多资源,源码.因为上面涉及到非常多天气信息,包含湿度,出行建议等,以及加入了全部城市代码的资源包.为了练手了解json的原理.我仅获取诚笃城市的最高温, ...

  8. Android---两个视图间的淡入淡出

    本文译自:http://developer.android.com/training/animation/crossfade.html 淡入淡出动画(也可以作为溶解动画)是指在渐渐的淡出一个UI组件的 ...

  9. 物联网操作系统HelloX开发人员入门指南

    HelloX开发人员入门指南 HelloX是聚焦于物联网领域的操作系统开发项目,能够通过百度搜索"HelloX".获取具体信息. 当前开发团队正在进一步招募中,欢迎您的了解和添加. ...

  10. Java 使用AES/CBC/PKCS7Padding 加解密字符串

    介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别要实现在java端用PKCS7Padding填充, ...