dom4j对于xml文件的一些操作
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XMLReader {
/**
*xml文档或节点转换为字符串
*/
public void xmlReader()throws Exception{
//创建SAXReader对象
SAXReader reader = new SAXReader();
//读取文件 转换成Document
Document document = reader.read(new File("H://DESKTOP//quyukeshi_cache.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 str = student1Node.asXML();
System.out.println("xml 字符串:" + str);
}
/**
* xml字符串转换为Document对象
*/
public void xmlToDocument()throws Exception{
String xmlStr = "<employee><empname>测试</empname><age>25</age><title>软件开发工程师</title></employee>";
Document document = DocumentHelper.parseText(xmlStr);
//把生成的xml文档存放在硬盘上 true代表是否换行
OutputFormat format = new OutputFormat(" ",true);
format.setEncoding("GBK");//设置编码格式
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("H://DESKTOP//Person.xml"),format);
xmlWriter.write(document);
xmlWriter.close();
}
public void createDocument()throws Exception{
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("employee");
Element empName = rootElement.addElement("empname");
empName.addElement("测试").addAttribute("婚姻", "单身").addText("小章");
Element empAge = rootElement.addElement("age");
empAge.setText("25");
Element empTitle = rootElement.addElement("title");
empTitle.setText("软件开发工程师");
//把生成的xml文档存放在硬盘上 true代表是否换行
OutputFormat format = new OutputFormat(" ",true);
format.setEncoding("GBK");//设置编码格式
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("H://DESKTOP//Person1.xml"),format);
xmlWriter.write(document);
xmlWriter.close();
}
public static void main(String[] args) throws Exception {
XMLReader handler = new XMLReader();
handler.xmlReader();
handler.xmlToDocument();
handler.createDocument();
}
}