/**
* JDOM
* 添加节点
* @param args
*/
public static void main1(String[] args) {
File file = new File("F:Stu.xml");
// 创建文档对象
Document doc = new Document();
// 创建节点
Element root = new Element("studentList");
Element student = new Element("student");
Element name = new Element("name");
Element sex = new Element("sex");
Element age = new Element("age");
// 为节点设置数据
student.setAttribute("stuNo", "s1001");
name.setText("张三");
sex.setText("男");
age.setText("25");
// 设置节点之间的关系
student.addContent(name);
student.addContent(sex);
student.addContent(age);
root.addContent(student);
doc.addContent(root);
// 将文档对象写入文件
XMLOutputter xo = new XMLOutputter();
try {
xo.output(doc, new FileOutputStream(file));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("写入成功!");
}
/**
* 追加数据
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
File file = new File("F:Stu.xml");
// 创建解析器
SAXBuilder sb = new SAXBuilder();
// 获得文档对象
Document doc = sb.build(file);
//获取根节点
Element root = doc.getRootElement();
// 创建子节点
Element student = new Element("student");
Element name = new Element("name");
Element sex = new Element("sex");
Element age = new Element("age");
// 为节点设置数据
student.setAttribute("stuNo", "s1002");
name.setText("李四");
sex.setText("男");
age.setText("25");
// 设置节点之间的关系
student.addContent(name);
student.addContent(sex);
student.addContent(age);
root.addContent(student);
// 将文档对象写入文件
XMLOutputter xo = new XMLOutputter();
try {
xo.output(doc, new FileOutputStream(file));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("添加成功!");
}
JDOM4J
public static void main1(String[] args) throws Exception {
// 创建路径
File file = new File("F:/Student.xml");
// 创建DOM对象
Document doc = DocumentHelper.createDocument();
// 创建根节点
Element StudentInfo = doc.addElement("StudentInfo");
// 创建子节点
Element Student = StudentInfo.addElement("Student");
Element name = Student.addElement("name");
Element sex = Student.addElement("sex");
// 赋值
Student.addAttribute("id", "t001");
name.addText("张三");
sex.addText("男");
// 写到XML中
XMLWriter xw = new XMLWriter(new FileOutputStream(file));
// 将DOM添加到XML中
xw.write(doc);
System.out.println("添加成功");
}
/**
* 在后面追加一个子节点
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 创建路径
File file = new File("F:/Student.xml");
// 创建解析器
SAXReader sr = new SAXReader();
// 获得文档对象
Document doc = sr.read(file);
//获取根节点
Element root = doc.getRootElement();
Element Student = root.addElement("Student");
Element name = Student.addElement("name");
Element sex = Student.addElement("sex");
// 赋值
Student.addAttribute("id", "t002");
name.addText("李四");
sex.addText("男");
// 写到XML中
XMLWriter xw = new XMLWriter(new FileOutputStream(file));
// 将DOM添加到XML中
xw.write(doc);
System.out.println("追加成功");
}