我用的是jdom,下面是代码:
@SuppressWarnings("unchecked")
public void delete()
{
users = root.getChildren();
iterator = users.iterator();
System.out.print("\n输入要删除的用户名:");
String uName = sc.next().trim();
//假定不存在该用户
boolean isUser = false;
while(iterator.hasNext()){
Element theUser = (Element)iterator.next();
String theName = theUser.getChild("name").getValue();
if(uName.equals(theName)){
isUser = true;//存在该用户
//找到要修改的元素
Element theSex = theUser.getChild("sex");
Element theAge = theUser.getChild("age");
Element thePhone = theUser.getChild("phone");
//Element user = theUser.getChild("user");
Element name = theUser.getChild("name");
theUser.removeContent(theSex);
theUser.removeContent(theAge);
theUser.removeContent(thePhone);
theUser.removeContent(name);
XMLOutputter xml = new XMLOutputter(Format.getPrettyFormat());
try{
xml.output(doc, new FileOutputStream(xmlFile));
}catch(Exception e){
e.printStackTrace();
}
System.out.println("\n删除成功!");
}
}
if(!isUser){
System.out.println("查无此用户");
}
}
}
删除之前xml文件:
即
女
3
3
删除之后只有这个:
为什么啊?求大神!!
java删除xml文件节点,主要方式是先解析整个xml文件,然后根据节点的编号,进行删除,代码如下:
package test;
import java.io.ioexception;
import javax.xml.parsers.documentbuilder;
import javax.xml.parsers.documentbuilderfactory;
import javax.xml.parsers.parserconfigurationexception;
import javax.xml.transform.transformer;
import javax.xml.transform.transformerconfigurationexception;
import javax.xml.transform.transformerexception;
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.nodelist;
import org.w3c.dom.text;
import org.xml.sax.saxexception;
public class xmloprate {
document doc;
documentbuilderfactory factory = documentbuilderfactory.newinstance();
documentbuilder builder;
nodelist imags;
string path;
public nodelist getimags() {
return imags;
}
public void setimags(nodelist imags) {
this.imags = imags;
}
public xmloprate(string path) {
super();
this.path = path;
system.out.println(system.getproperty("user.dir"));
}
public void readxml(){
try {
builder = factory.newdocumentbuilder();
document doc=builder.parse(path);
doc.normalize();
nodelist imags =doc.getelementsbytagname("imags");
this.setimags(imags);
for (int i=0;i
我要举报