java使用dom4j操作xml示例代码
dom4j是一个非常优秀的java xml api,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源工具。可以在这个地址http://dom4j.sourceforge.net进行下载。
这里我们使用到的dom4j是dom4j-1.6.1这个版本,我们只需要使用到如下两个jar包:
dom4j-1.6.1.jar
commons-io-2.4.jar
1、dom4j读取xml字符串
import org.dom4j.document;
import org.dom4j.documentexception;
import org.dom4j.documenthelper;
import org.dom4j.element;
public class testreadxmlstring {
public static void main(string[] args) throws documentexception {
string readline = "<?xml version=\"1.0\" encoding=\"utf-8\"?><students><student sid=\"001\"> <id>001</id><name>灰机</name> <age>18</age> </student></students>";
document document = documenthelper.parsetext(readline);
element rootelm = document.getrootelement();
system.out.println("rootelement: " + rootelm.getname());
element student = rootelm.element("student");
element id = student.element("id");
element name = student.element("name");
element age = student.element("age");
system.out.println(id.gettext());
system.out.println(name.gettext());
system.out.println(age.gettext());
}
}
2、dom4j创建xml文件
import org.dom4j.document;
import org.dom4j.documenthelper;
import org.dom4j.element;
import org.dom4j.io.outputformat;
public class testwritexmlstring {
public static void main(string[] args) {
outputformat format = outputformat.createprettyprint();
// 1. 构造空的document
document doc = documenthelper.createdocument();
doc.addcomment("this is a comment");
// 2. 构造根元素
element rootelmt = doc.addelement("users");
rootelmt.addnamespace("test", "www.test.com");
element userelmt = rootelmt.addelement("user");
userelmt.addattribute("number", "1001");
userelmt.addelement("name").settext("zhangsan");
userelmt.addelement("age").settext("20");
userelmt.addelement("gender").settext("mail");
element userelmt2 = rootelmt.addelement("user");
userelmt.addattribute("number", "1002");
userelmt2.addelement("name").settext("zhangsan");
userelmt2.addelement("age").settext("20");
userelmt2.addelement("gender").settext("mail");
system.out.println(doc.asxml().replaceall("\n", ""));
}
}
3、读取或写xml文件
读取xml文件
saxreader reader = new saxreader();
string path = "e:/workspaces/myeclipse 8.6/xmltest/file/student.xml";
document document = reader.read(new file(path));
写xml文件
outputformat format = outputformat.createprettyprint();
format.setencoding("utf-8");// 设置xml文件的编码格式
string filepath = "e:/workspaces/myeclipse 8.6/xmltest/file/student.xml";
document document = documenthelper.createdocument();
doc.addcomment("this is a comment");
/创建document内容
xmlwriter writer = new xmlwriter(new filewriter(filepath), format);//写入指定的文件
writer.write(document);
writer.close();