1、xml文档或节点转换为字符串
//xml文档或节点转换为字符串
@Test
public void test5()throws Exception{
//创建SAXReader对象
SAXReader reader = new SAXReader();
//读取文件 转换成Document
Document document = reader.read(new File("src/cn/com/yy/dom4j/s.xml"));
//document转换为String字符串
String documentStr = document.asXML();
System.out.println("document 字符串:" + documentStr);
//获取根节点
Element root = document.getRootElement();
//根节点转换为String字符串
String rootStr = root.asXML();
System.out.println("root 字符串:" + rootStr);
//获取其中student1节点
Element student1Node = root.element("student1");
//student1节点转换为String字符串
String student1Str = student1Node.asXML();
System.out.println("student1 字符串:" + student1Str);
}
2、xml字符串转换为Document对象
//xml字符串转换为Document对象
@Test
public void test6()throws Exception{
String xmlStr = "<employee><empname>@残缺的孤独</empname><age>25</age><title>软件开发工程师</title></employee>";
Document document = DocumentHelper.parseText(xmlStr);
//写入emp1.xml文件
writerDocumentToNewFile(document);
}
3、新建Document
我们使用dom4j新建document对象,并写入文件中。
//新建Document对象,添加节点元素并写入文件
@Test
public void test7()throws Exception{
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("employee");
Element empName = rootElement.addElement("empname");
empName.setText("@残缺的孤独");
Element empAge = rootElement.addElement("age");
empAge.setText("25");
Element empTitle = rootElement.addElement("title");
empTitle.setText("软件开发工程师");
//写入文档emp.xml
writerDocumentToNewFile(document);
}