使用Dom4j来更新xml

通过java程序来实现对xml文件内部的更新

xml和Schema参考:xxxx

说明:

跟遍历一样都是要获取xml文件和设置Document对象。

1.写入的核心是addElement()方法,root代表的是xml根节点<students>,root.addElement(“student”)就是在<students>里面设置一个<student>标签

2.student.addAttribute(“no”,”c001″)   设置<student>标签的属性。属性名为:name; 值为:c001;

3.student.addElement(“name”)   在<student>标签中添加一个<name>标签

4.name.setText(“喷火龙”);    设置<name>标签文本信息为:”喷火龙”

5.Writer e = new OutputStreamWriter(new FileOutputStream(file),”UTF-8″); 写入xml需要方法。当把包都倒进去后,会报错。此时会出现报错,只要把下面的catch()里面修改成Exception e就可以

6.记得写上e.close(); 才能完整运行

7.可以通过eclipse左上方的Source-Format来整理代码

package com.cc.schemajava1;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.dom4j.Document;

import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class StudentDemoWrite {	
	public void writeing() {
		String file = "C:\Users\Jun\Desktop\java web\jsp\day3\XML2\src\com\cc\schema1\studentDemo.xml";
		SAXReader read = new SAXReader();
		try {
			Document document = read.read(file);
			Element root = document.getRootElement();		//获得跟节点
			Element student = root.addElement("student");
			student.addAttribute("no", "c001");
			Element name = student.addElement("name");
			name.setText("喷火龙");

			student.addElement("age").setText("23");
			student.addElement("scorce").setText("34");

			Element school = student.addElement("schoolname");

			school.addElement("garder").setText("大三");
			school.addElement("class").setText("6班");
			
			Writer e = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
			document.write(e);
			e.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		StudentDemoWrite test = new StudentDemoWrite();
		test.writeing();
	}
}
物联沃分享整理
物联沃-IOTWORD物联网 » 使用Dom4j来更新xml

发表评论

提供最优质的资源集合

立即查看 了解详情