DOM4J实例

package cn.csdn.dom;

import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
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;
import org.junit.Test;

public class Dom4jTest {

private static Document doc;
/*转载xml文档 到xml文档的Document对象*/
static{
//创建dom4j解析器对象
SAXReader reader = new SAXReader();
//解析器对象 解析指定的xml文档 返回 Document对象
try {
doc = reader.read(new File("src/book.xml"));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@Test
public void root(){
System.out.println(doc);
//怎么获取文档的根结点呢
Element root = doc.getRootElement();
listElements(root);
}
//遍历整个文档的元素节点
private void listElements(Element root) {
System.out.println("元素节点名称:"+root.getName());
Iterator<Node> it = root.elementIterator();
while(it.hasNext()){
Node node = it.next();
listElements((Element) node);
}
}

//查找指定的元素节点
@Test
public void findElement(){
Element root = doc.getRootElement();
Element book = root.element("书");
Element name = book.element("书名");
System.out.println(name.getText());
}


//在指定位置添加节点
@Test
public void addElement() throws Exception{
Element root = doc.getRootElement();
Element book = root.element("书");
Element name = book.element("书名");

Element author = DocumentHelper.createElement("作者");
author.setText("大海");
List<Node> nodes = book.elements();
nodes.add(1, author);




OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter( "src/book.xml" ));
writer.write(doc);
writer.close();


}


//在指定位置删除节点
@Test
public void deleteElement() throws Exception{
Element root = doc.getRootElement();
Element book = root.element("书");
Element name = book.element("书名");
name.remove(name.element("作者"));


OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter( "src/book.xml" ));
writer.write(doc);
writer.close();


}


//遍历某个元素节点的属性
@Test
public void attr(){
Element root = doc.getRootElement();
int count = root.attributeCount();
System.out.println(count);
for(int i=0;i<count;i++){
Attribute attribute = root.attribute(i);
System.out.println(attribute.getName()+"=="+attribute.getValue());
}

}

//删除某个元素节点的属性
@Test
public void delAttr()throws Exception{
Element root = doc.getRootElement();
/*
Attribute xm = root.attribute("xm");

root.remove(xm);*/
/*root.addAttribute("xm", "cccc");*/
Attribute xm = root.attribute("xm");
xm.setText("修改呢");


OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileWriter( "src/book.xml" ));
writer.write(doc);
writer.close();

}
}

你可能感兴趣的:(java,xml,dom,csdn)