package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import javax.sql.rowset.spi.XmlWriter;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class xml4Demo {
public void CreateXml() throws DocumentException{
File file=new File("E://new.xml");
Document doc=null;
if(!file.exists()){
//创建一个xmlwend
doc=DocumentHelper.createDocument();
}else{
doc=new SAXReader().read(new File("E://new.xml"));
}
//写注释
doc.addComment("这是注释");
//创建根节点
Element root=doc.addElement("students");
//给student 添加一个节点
Element stuEle=root.addElement("student");
stuEle.addAttribute("id", "1");
Element nameEle=stuEle.addElement("name");
nameEle.addText("张三");
//设置格式化xml
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
Writer out;
try {
out =new FileWriter("E://new.xml");
XMLWriter writer =new XMLWriter(out,format);
writer.write(doc);
writer.close();
System.out.println("生成文件成功");
} catch (Exception e) {
System.out.println("生成xml文件失败");
e.printStackTrace();
// TODO: handle exception
}
}
//修改xml
public void updateXml(String id) throws IOException, DocumentException{
//读取文件
Document doc=new SAXReader().read(new File("E://new.xml"));
Element stuEle =(Element) doc.selectSingleNode("/students/student[@id='"+id+"']");//寻找节点
stuEle.element("name").setText("haha");//设置值
FileOutputStream out =new FileOutputStream("E://new.xml");
OutputFormat format= OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer =new XMLWriter(out,format);
writer.write(doc);
writer.close();
}
//删除
public void deleteXml(String id) throws DocumentException, FileNotFoundException, Exception{
Document doc=new SAXReader().read("E://new.xml");
Element stuEle=(Element) doc.selectSingleNode("/students/student[@id='"+id+"']");
stuEle.detach();
FileOutputStream out =new FileOutputStream("E://new.xml");
OutputFormat format= OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer =new XMLWriter(out,format);
writer.write(doc);
writer.close();
}
public static void main(String[] args) throws DocumentException, IOException {
xml4Demo dome=new xml4Demo();
// dome.CreateXml();
dome.updateXml("25");
}
}