import org.dom4j.*;
import org.dom4j.io.*;
import java.io.*;
import java.util.*;
public class test {
//写入
public void cXML(){
try {
Document document = DocumentHelper.createDocument();
Element friendsElement = document.addElement("scores");
Element friends1Element = friendsElement.addElement("JAVA");
Element friends2Element = friendsElement.addElement("C");
Element friends3Element = friendsElement.addElement("JS");
friends1Element.setText("85");
friends2Element.setText("80");
friends3Element.setText("90");
XMLWriter writer = new XMLWriter(new FileWriter(new File("c:/test.xml")));
writer.write(document);
writer.close();
System.out.println("创建XML成功");
}catch (Exception err) {
err.printStackTrace();
}
}
//读取
public void read(){
try{
File f = new File("c:/test.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(f);
Element root = doc.getRootElement();
System.out.println("已找到XML");
System.out.println("节点JAVA下的值为:"+root.elementText("JAVA"));
System.out.println("节点C下的值为:"+root.elementText("C"));
System.out.println("节点JS下的值为:"+root.elementText("JS"));
}
catch(Exception err){
err.printStackTrace();
}
}
public static void main(String[] args){
test a=new test();
a.cXML();//写入
a.read();//读取
}
}
(1)用程序创建一个xml文件c:/test.xml, 为该文件增加学生成绩节点内容如下:
<scores>
<Java>85</Java>
<C++>80</C++>
<JS>90</JS>
</scores>