dom4j读写xml文件
程序员文章站
2022-05-29 11:34:11
...
1. 参考 dom4j-1.6.1\dom4j-1.6.1\docs\guide.html
2. Jom4jTest.java文件
/**
*
*/
2. Jom4jTest.java文件
/**
*
*/
package com.jquerypro.test;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* @author myhello
*
*/
public class Jom4jTest {
private Element rootElm = null; //根结点
private String FILE_NAME = "com/jquerypro/test/sys-config.xml";
private Jom4jTest instance = null;
private Jom4jTest(){
try {
SAXReader reader = new SAXReader();
//URL urlFile = Thread.currentThread().getContextClassLoader().getResource(""); //到达class
Document document = reader.read(Thread.currentThread().getContextClassLoader().getResourceAsStream(FILE_NAME));
rootElm = document.getRootElement();
System.out.println("根结点名称="+rootElm.getName());
} catch (Exception e) {
System.out.println(" 没有找到文件");
}
}
public Jom4jTest getInstance(){
if(instance == null){
instance = new Jom4jTest();
}
return instance;
}
// 读取一些信息
public void getInfo(){
Node jdbcElm = rootElm.selectSingleNode("//system-config/jdbc-info/driver-name");
System.out.println("selectNode="+jdbcElm.getText());
//System.out.println(rootElm.asXML());
//遍历元素
List nodeList = rootElm.selectNodes("//system-config/beans/bean");
for ( Iterator it = nodeList.iterator(); it.hasNext(); ) {
Element elm = (Element)it.next();
System.out.println("元素的内容="+elm.getText());
//属性遍历
for ( Iterator i = elm.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
System.out.println("元素的属性名和值:"+attribute.getName()+"="+attribute.getStringValue());
}
}
}
//创建document对象 //DocumentHelper
public Document createDoc(){
Document document = DocumentHelper.createDocument();
Element rootElm = document.addElement( "students" );
Element student1 = rootElm.addElement( "student" )
.addAttribute( "id", "001" )
.addAttribute( "username", "hello1" )
.addText( "学生1" );
Element student2 = rootElm.addElement( "student" )
.addAttribute( "id", "002" )
.addAttribute( "username", "hello2" )
.addText( "学生2" );
return document;
}
public void savaXML(String filePath) throws Exception{
XMLWriter writer = new XMLWriter(new FileOutputStream(filePath));
Document document = createDoc();
writer.write(document);
//查看字符串
String docStr = document.asXML();
//System.out.println("docStr="+docStr);
// Pretty print the document to System.out
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
writer = new XMLWriter( System.out, format );
writer.write( document );
}
public static void main(String[] args) throws Exception {
Jom4jTest test= new Jom4jTest();
test.savaXML("d:/xml_test.xml");
}
}