dom4j读写xml简单demo

package com.protocol;

import java.io.*;
import java.util.List;
import org.dom4j.*;
import org.dom4j.io.*;

public class Dom4jDemo {

    public void createXml(String fileName) {

        DocumentFactory factory = new DocumentFactory();
        Document document = factory.createDocument();
        Element root = document.addElement("root");
        for(Integer i=0; i < 2; ++i)
        {
            Element book = root.addElement("book");
            book.addAttribute("id",i.toString());
            book.addAttribute("name","bookname");

            Element author = book.addElement("author");
            author.setText("dalangge");

            Element price = book.addElement("price");
            price.setText("15");
        }

        try {
            FileWriter fw = new FileWriter(fileName);
            OutputFormat format = new OutputFormat("  ",true,"gb2312");
            XMLWriter writer = new XMLWriter(fw,format);
            writer.write(document);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void parserXml(String fileName) {
        try {
            File f = new File(fileName);
            InputStream in = new FileInputStream(f);
            SAXReader reader = new SAXReader();
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            readNode(root);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public void readNode(Element root) {
        if (root == null) return;

        System.out.println(root.getName()+":"+(String)root.getData());

        // 获取属性
        List<Attribute> attrs = root.attributes();
        if (attrs != null && attrs.size() > 0) {
            for (Attribute attr : attrs) {
                System.out.println(attr.getName() + ": " + attr.getValue());
            }
        }
        // 获取他的子节点
        List<Element> childNodes = root.elements();
        for (Element e : childNodes) {
            readNode(e);
        }
    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值