dom4j读写xml资料

dom4j读写xml文件

dom4j读写xml文件
首先我们给出一段示例程序:
dom4j读写xml资料import java.io.File;
dom4j读写xml资料
import java.io.FileWriter;
dom4j读写xml资料
import java.util.Iterator;
dom4j读写xml资料
dom4j读写xml资料
import org.dom4j.Document;
dom4j读写xml资料
import org.dom4j.DocumentHelper;
dom4j读写xml资料
import org.dom4j.Element;
dom4j读写xml资料
import org.dom4j.io.OutputFormat;
dom4j读写xml资料
import org.dom4j.io.SAXReader;
dom4j读写xml资料
import org.dom4j.io.XMLWriter;
dom4j读写xml资料
dom4j读写xml资料
public class DOM4JTest {
dom4j读写xml资料
dom4j读写xml资料    
/** */
dom4j读写xml资料    
/** */
dom4j读写xml资料    
/** */
dom4j读写xml资料    
/**
dom4j读写xml资料     * DOM4J读写XML示例
dom4j读写xml资料     * 
dom4j读写xml资料     * 
@param args
dom4j读写xml资料     * 
@throws Exception
dom4j读写xml资料     
*/

dom4j读写xml资料    
public static void main(String[] args) {
dom4j读写xml资料        
try {
dom4j读写xml资料            XMLWriter writer 
= null;// 声明写XML的对象
dom4j读写xml资料
            SAXReader reader = new SAXReader();
dom4j读写xml资料
dom4j读写xml资料            OutputFormat format 
= OutputFormat.createPrettyPrint();
dom4j读写xml资料            format.setEncoding(
"GBK");// 设置XML文件的编码格式
dom4j读写xml资料

dom4j读写xml资料            String filePath 
= "d:\\student.xml";
dom4j读写xml资料            File file 
= new File(filePath);
dom4j读写xml资料            
if (file.exists()) {
dom4j读写xml资料                Document document 
= reader.read(file);// 读取XML文件
dom4j读写xml资料
                Element root = document.getRootElement();// 得到根节点
dom4j读写xml资料
                boolean bl = false;
dom4j读写xml资料                
for (Iterator i = root.elementIterator("学生"); i.hasNext();) {
dom4j读写xml资料                    Element student 
= (Element) i.next();
dom4j读写xml资料                    
if (student.attributeValue("sid").equals("001")) {
dom4j读写xml资料                        
// 修改学生sid=001的学生信息
dom4j读写xml资料
                        student.selectSingleNode("姓名").setText("王五");
dom4j读写xml资料                        student.selectSingleNode(
"年龄").setText("25");
dom4j读写xml资料
dom4j读写xml资料                        writer 
= new XMLWriter(new FileWriter(filePath), format);
dom4j读写xml资料                        writer.write(document);
dom4j读写xml资料                        writer.close();
dom4j读写xml资料                        bl 
= true;
dom4j读写xml资料                        
break;
dom4j读写xml资料                    }

dom4j读写xml资料                }

dom4j读写xml资料                
if (bl) {
dom4j读写xml资料                    
// 添加一个学生信息
dom4j读写xml资料
                    Element student = root.addElement("学生");
dom4j读写xml资料                    student.addAttribute(
"sid""100");
dom4j读写xml资料                    Element sid 
= student.addElement("编号");
dom4j读写xml资料                    sid.setText(
"100");
dom4j读写xml资料                    Element name 
= student.addElement("姓名");
dom4j读写xml资料                    name.setText(
"嘎嘎");
dom4j读写xml资料                    Element sex 
= student.addElement("性别");
dom4j读写xml资料                    sex.setText(
"");
dom4j读写xml资料                    Element age 
= student.addElement("年龄");
dom4j读写xml资料                    age.setText(
"21");
dom4j读写xml资料
dom4j读写xml资料                    writer 
= new XMLWriter(new FileWriter(filePath), format);
dom4j读写xml资料                    writer.write(document);
dom4j读写xml资料                    writer.close();
dom4j读写xml资料                }

dom4j读写xml资料            }
 else {
dom4j读写xml资料                
// 新建student.xml文件并新增内容
dom4j读写xml资料
                Document _document = DocumentHelper.createDocument();
dom4j读写xml资料                Element _root 
= _document.addElement("学生信息");
dom4j读写xml资料                Element _student 
= _root.addElement("学生");
dom4j读写xml资料                _student.addAttribute(
"sid""001");
dom4j读写xml资料                Element _id 
= _student.addElement("编号");
dom4j读写xml资料                _id.setText(
"001");
dom4j读写xml资料                Element _name 
= _student.addElement("姓名");
dom4j读写xml资料                _name.setText(
"灰机");
dom4j读写xml资料                Element _age 
= _student.addElement("年龄");
dom4j读写xml资料                _age.setText(
"18");
dom4j读写xml资料
dom4j读写xml资料                writer 
= new XMLWriter(new FileWriter(file), format);
dom4j读写xml资料                writer.write(_document);
dom4j读写xml资料                writer.close();
dom4j读写xml资料            }

dom4j读写xml资料            System.out.println(
"操作结束! ");
dom4j读写xml资料        }
 catch (Exception e) {
dom4j读写xml资料            e.printStackTrace();
dom4j读写xml资料        }

dom4j读写xml资料
dom4j读写xml资料    }

dom4j读写xml资料}

执行结果应该是这样:

dom4j读写xml资料

循环解析节点:
dom4j读写xml资料private void getAllNodes(String xml) {
dom4j读写xml资料        
try {
dom4j读写xml资料            Document authtmp 
= DocumentHelper.parseText(xml);
dom4j读写xml资料            List
<Element> list = authtmp.selectNodes("//sms/node");
dom4j读写xml资料            
for (int j = 0; j < list.size(); j++{
dom4j读写xml资料                Element node 
= (Element) list.get(j);
dom4j读写xml资料                nodeByNodes(node);
dom4j读写xml资料            }

dom4j读写xml资料        }
 catch (Exception e) {
dom4j读写xml资料            e.printStackTrace();
dom4j读写xml资料        }

dom4j读写xml资料    }

dom4j读写xml资料
dom4j读写xml资料    
private void nodeByNodes(Element node) {
dom4j读写xml资料        
if (node.element("node"!= null{
dom4j读写xml资料            String id 
= node.attributeValue("id");
dom4j读写xml资料            String name 
= node.attributeValue("name");
dom4j读写xml资料            System.out.print(id 
+ "-------");
dom4j读写xml资料            System.out.println(name);
dom4j读写xml资料            
for (Iterator i = node.elementIterator("node"); i.hasNext();) {
dom4j读写xml资料                Element newNode 
= (Element) i.next();
dom4j读写xml资料                nodeByNodes(newNode);
dom4j读写xml资料            }

dom4j读写xml资料        }
 else {
dom4j读写xml资料            String id 
= node.attributeValue("id");
dom4j读写xml资料            String name 
= node.attributeValue("name");
dom4j读写xml资料            System.out.print(id 
+ "-------");
dom4j读写xml资料            System.out.println(name);
dom4j读写xml资料        }

dom4j读写xml资料    }

其次DOM4J的解释

一.Document对象相关

1.读取XML文件,获得document对象.
dom4j读写xml资料      SAXReader reader = new SAXReader();
dom4j读写xml资料      Document   document = reader.read(new File("input.xml"));

2.解析XML形式的文本,得到document对象.
dom4j读写xml资料      String text = "<members></members>";
dom4j读写xml资料      Document document = DocumentHelper.parseText(text);

3.主动创建document对象.
dom4j读写xml资料      Document document = DocumentHelper.createDocument();
dom4j读写xml资料      Element root = document.addElement("members");// 创建根节点

二.节点相关

1.获取文档的根节点.
dom4j读写xml资料     Element rootElm = document.getRootElement();

2.取得某节点的单个子节点.
dom4j读写xml资料     Element memberElm=root.element("member");// "member"是节点名

3.取得节点的文字
dom4j读写xml资料     String text=memberElm.getText();
也可以用:
dom4j读写xml资料     String text=root.elementText("name");
这个是取得根节点下的name字节点的文字.

4.取得某节点下名为"member"的所有字节点并进行遍历.
dom4j读写xml资料List nodes = rootElm.elements("member");
dom4j读写xml资料
dom4j读写xml资料for (Iterator it = nodes.iterator(); it.hasNext();) {
dom4j读写xml资料    Element elm 
= (Element) it.next();
dom4j读写xml资料   // do something
dom4j读写xml资料}

5.对某节点下的所有子节点进行遍历.
dom4j读写xml资料 for(Iterator it=root.elementIterator();it.hasNext();){
dom4j读写xml资料                 Element element 
= (Element) it.next();
dom4j读写xml资料                
// do something
dom4j读写xml资料
             }

6.在某节点下添加子节点.
dom4j读写xml资料Element ageElm = newMemberElm.addElement("age");

7.设置节点文字.
dom4j读写xml资料ageElm.setText("29");

8.删除某节点.
dom4j读写xml资料parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点

9.添加一个CDATA节点.
dom4j读写xml资料         Element contentElm = infoElm.addElement("content");
dom4j读写xml资料         contentElm.addCDATA(diary.getContent());

            contentElm.getText(); // 特别说明:获取节点的CDATA值与获取节点的值是一个方法
            contentElm.clearContent(); //清除节点中的内容,CDATA亦可


三.属性相关.
1.取得某节点下的某属性
dom4j读写xml资料             Element root=document.getRootElement();    
dom4j读写xml资料             Attribute attribute
=root.attribute("size");// 属性名name

2.取得属性的文字
dom4j读写xml资料             String text=attribute.getText();
也可以用:
dom4j读写xml资料String text2=root.element("name").attributeValue("firstname");
这个是取得根节点下name字节点的属性firstname的值.

3.遍历某节点的所有属性
dom4j读写xml资料  Element root=document.getRootElement();    
dom4j读写xml资料            
for(Iterator it=root.attributeIterator();it.hasNext();){
dom4j读写xml资料                 Attribute attribute 
= (Attribute) it.next();
dom4j读写xml资料                 String text
=attribute.getText();
dom4j读写xml资料                 System.out.println(text);
dom4j读写xml资料             }

4.设置某节点的属性和文字.
dom4j读写xml资料newMemberElm.addAttribute("name""sitinspring");

5.设置属性的文字
dom4j读写xml资料             Attribute attribute=root.attribute("name");
dom4j读写xml资料             attribute.setText(
"sitinspring");

6.删除某属性
dom4j读写xml资料             Attribute attribute=root.attribute("size");// 属性名name
dom4j读写xml资料
             root.remove(attribute);

四.将文档写入XML文件.
1.文档中全为英文,不设置编码,直接写入的形式.
dom4j读写xml资料XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
dom4j读写xml资料writer.write(document);
dom4j读写xml资料writer.close();

2.文档中含有中文,设置编码格式写入的形式.
dom4j读写xml资料             OutputFormat format = OutputFormat.createPrettyPrint();
dom4j读写xml资料             format.setEncoding(
"GBK");    // 指定XML编码        
dom4j读写xml资料
             XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);
dom4j读写xml资料            
dom4j读写xml资料             writer.write(document);
dom4j读写xml资料             writer.close();

五.字符串与XML的转换
1.将字符串转化为XML
dom4j读写xml资料String text = "<members> <member>sitinspring</member> </members>";
dom4j读写xml资料Document document 
= DocumentHelper.parseText(text);

2.将文档或节点的XML转化为字符串.
dom4j读写xml资料             SAXReader reader = new SAXReader();
dom4j读写xml资料             Document   document 
= reader.read(new File("input.xml"));            
dom4j读写xml资料             Element root
=document.getRootElement();                
dom4j读写xml资料             String docXmlText
=document.asXML();
dom4j读写xml资料             String rootXmlText
=root.asXML();
dom4j读写xml资料             Element memberElm
=root.element("member");
dom4j读写xml资料             String memberXmlText
=memberElm.asXML();
转自:http://www.blogjava.net/biiau/archive/2008/09/24/231005.html