java用dom4j操作XML
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jDmeo {
static void readXML(String path){
SAXReader reader=new SAXReader();//构建sax读取对象
try {
Document doc=reader.read(path);//获取文档对象
Element root=doc.getRootElement();//获取根节点
System.out.println("根节点:"+root.getName());
Iterator it=root.elementIterator();//获取根节点下面的所有子节点
while(it.hasNext()){
Element el=(Element) it.next();//遍历出根节点下面的单个节点
System.out.println(el.elementText("NO"));
System.out.println(el.element("NO").attributeValue("DATE"));
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
static void findXML(String path){
SAXReader reader=new SAXReader();//构建sax读取对象
try {
Document doc=reader.read(path);//获取文档对象
Element root=doc.getRootElement();//获取根节点
Node node=doc.selectSingleNode("//Result/VALUE/NO");
System.out.println(node.getText());
} catch (DocumentException e) {
e.printStackTrace();
}
}
static void writeXML(){
//构建xml输出对象
try {
XMLWriter writer=new XMLWriter(new FileWriter("d:/link.xml"));
Document doc=DocumentHelper.createDocument();//创建文档对象
Element root=doc.addElement("学生信息");
root.addElement("学生").addElement("姓名").addAttribute("性别", "男").addText("张三");//构建子节点,属性值和显示文本
root.addElement("学生").addElement("姓名").addAttribute("性别", "女").addText("历史");//构建子节点,属性值和显示文本
writer.write(doc);//输出文档对象
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//Dom4jDmeo.readXML("d:/text.xml");
//Dom4jDmeo.writeXML();
Dom4jDmeo.findXML("d:/text.xml");
}
}