首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

.dom4j读写xml资料

2012-12-20 
.dom4j读写xml文件http://www.blogjava.net/biiau/archive/2008/09/24/231005.html首先我们给出一段示例程

.dom4j读写xml文件
http://www.blogjava.net/biiau/archive/2008/09/24/231005.html

首先我们给出一段示例程序:

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

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 DOM4JTest {

    /** *//** */
    /** *//** */
    /** *//** */
    /** *//**
     * DOM4J读写XML示例
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) {
        try {
            XMLWriter writer = null;// 声明写XML的对象
            SAXReader reader = new SAXReader();

            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("GBK");// 设置XML文件的编码格式

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

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

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

                writer = new XMLWriter(new FileWriter(file), format);
                writer.write(_document);
                writer.close();
            }
            System.out.println("操作结束! ");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
执行结果应该是这样:



循环解析节点:

private void getAllNodes(String xml) {
        try {
            Document authtmp = DocumentHelper.parseText(xml);
            List<Element> list = authtmp.selectNodes("//sms/node");
            for (int j = 0; j < list.size(); j++) {
                Element node = (Element) list.get(j);
                nodeByNodes(node);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void nodeByNodes(Element node) {
        if (node.element("node") != null) {
            String id = node.attributeValue("id");
            String name = node.attributeValue("name");
            System.out.print(id + "-------");
            System.out.println(name);
            for (Iterator i = node.elementIterator("node"); i.hasNext();) {
                Element newNode = (Element) i.next();
                nodeByNodes(newNode);
            }
        } else {
            String id = node.attributeValue("id");
            String name = node.attributeValue("name");
            System.out.print(id + "-------");
            System.out.println(name);
        }
    }
其次DOM4J的解释

一.Document对象相关

1.读取XML文件,获得document对象.

      SAXReader reader = new SAXReader();
      Document   document = reader.read(new File("input.xml"));
2.解析XML形式的文本,得到document对象.

      String text = "<members></members>";
      Document document = DocumentHelper.parseText(text);
3.主动创建document对象.

      Document document = DocumentHelper.createDocument();
      Element root = document.addElement("members");// 创建根节点
二.节点相关

1.获取文档的根节点.

     Element rootElm = document.getRootElement();
2.取得某节点的单个子节点.

     Element memberElm=root.element("member");// "member"是节点名
3.取得节点的文字

     String text=memberElm.getText();也可以用:

     String text=root.elementText("name");这个是取得根节点下的name字节点的文字.

4.取得某节点下名为"member"的所有字节点并进行遍历.

List nodes = rootElm.elements("member");

for (Iterator it = nodes.iterator(); it.hasNext();) {
    Element elm = (Element) it.next();
   // do something
}
5.对某节点下的所有子节点进行遍历.

for(Iterator it=root.elementIterator();it.hasNext();){
                 Element element = (Element) it.next();
                // do something
             }
6.在某节点下添加子节点.

Element ageElm = newMemberElm.addElement("age");
7.设置节点文字.

ageElm.setText("29");
8.删除某节点.

parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点
9.添加一个CDATA节点.

         Element contentElm = infoElm.addElement("content");
         contentElm.addCDATA(diary.getContent());

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

三.属性相关.
1.取得某节点下的某属性

             Element root=document.getRootElement();   
             Attribute attribute=root.attribute("size");// 属性名name
2.取得属性的文字

             String text=attribute.getText();也可以用:

String text2=root.element("name").attributeValue("firstname");这个是取得根节点下name字节点的属性firstname的值.

3.遍历某节点的所有属性

  Element root=document.getRootElement();   
            for(Iterator it=root.attributeIterator();it.hasNext();){
                 Attribute attribute = (Attribute) it.next();
                 String text=attribute.getText();
                 System.out.println(text);
             }
4.设置某节点的属性和文字.

newMemberElm.addAttribute("name", "sitinspring");
5.设置属性的文字

             Attribute attribute=root.attribute("name");
             attribute.setText("sitinspring");
6.删除某属性

             Attribute attribute=root.attribute("size");// 属性名name
             root.remove(attribute);
四.将文档写入XML文件.
1.文档中全为英文,不设置编码,直接写入的形式.

XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
writer.close();
2.文档中含有中文,设置编码格式写入的形式.

             OutputFormat format = OutputFormat.createPrettyPrint();
             format.setEncoding("GBK");    // 指定XML编码       
             XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);
           
             writer.write(document);
             writer.close();
五.字符串与XML的转换
1.将字符串转化为XML

String text = "<members> <member>sitinspring</member> </members>";
Document document = DocumentHelper.parseText(text);
2.将文档或节点的XML转化为字符串.

             SAXReader reader = new SAXReader();
             Document   document = reader.read(new File("input.xml"));           
             Element root=document.getRootElement();               
             String docXmlText=document.asXML();
             String rootXmlText=root.asXML();
             Element memberElm=root.element("member");
             String memberXmlText=memberElm.asXML();

热点排行