import org.xml.sax.XMLReader;
import javax.sql.rowset.spi.XmlWriter;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
-
Created with IntelliJ IDEA.
-
User: a549238
-
Date: 3/14/13
-
Time: 1:07 PM
-
To change this template use File | Settings | File Templates.
*/
public class XMLManagerByDom4j {
private final String filepath;
public XMLManagerByDom4j(String filepath)
{
this.filepath=filepath;
}/**
- init XML File
- @param strudentList
*/
public void createXMLFile(List strudentList)
{
Document document= DocumentHelper.createDocument();
Element root=DocumentHelper.createElement(“root”);
document.setRootElement(root); // 设置root节点的另一种方法:document.addElement(“root”) ;
Element element=null;
for(Student student:strudentList)
{
element=root.addElement(“student”);
element.addElement(“name”).addText(student.getName());
element.addElement(“sex”).addText(student.getSex());
element.addElement(“age”).addText(String.valueOf(student.getAge()));
}
root.appendContent(element); //这是添加元素的另一种方式
saveFile(document,filepath);
}
public List getAllStudents()
{
List studentList=new ArrayList();
try {
SAXReader saxReader=new SAXReader();
Document document=saxReader.read(new File(filepath)) ;
Element root=document.getRootElement();
Iterator elementIterator=root.elementIterator(“student”);
Element element=null,tempelement2=null;
while(elementIterator.hasNext())
{
Student student=new Student();
element=elementIterator.next();
for(Iterator tempelement=element.elementIterator();tempelement.hasNext()😉
{
tempelement2=tempelement.next();
if(tempelement2.getName().equals(“name”))
student.setName(tempelement2.getText());
else if(tempelement2.getName().equals(“sex”))
student.setSex(tempelement2.getText());
else if(tempelement2.getName().equals(“age”))
student.setAge(Integer.parseInt(tempelement2.getText()));
studentList.add(student) ;
}
}
}catch (DocumentException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return studentList;
}public Student getStudentByName(String name)
{
List studentList=getAllStudents();
for(Student student:studentList)
if(student.getName().equals(name))
return student;
return null;
}public void delByName(String name)
{
try {
SAXReader saxReader=new SAXReader();
Document document=saxReader.read(new File(filepath)) ;
Element root=document.getRootElement();
Iterator elementIterator=root.elementIterator(“student”);
Element element=null,tempelement2=null;
while(elementIterator.hasNext())
{
Student student=new Student();
element=elementIterator.next();
for(Iterator tempelement=element.elementIterator();tempelement.hasNext()😉
{
tempelement2=tempelement.next();
if(tempelement2.getName().equals(“name”))
if(tempelement2.getText().equals(name))
tempelement.remove();
}
}
saveFile(document,filepath);