码迷,mamicode.com
首页 > 其他好文 > 详细

dom4j读写XML文件

时间:2015-06-11 16:30:43      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

XML文件格式:

<?xml version="1.0" encoding="UTF-8"?>
<company> 
    <employee name="zhangsan" value="张三"/>  
    <employee name="lisi" value="李四"/>  
    <employee name="wangwu" value="王五"/>  
</company>

 

dom4j读写方法:

/**
     * 读取
     */
    public static void read() {
        try {
            File xmlFile = new File("d://company.xml");
            Document document = new SAXReader().read(xmlFile);
            List<Element> elements = document.selectNodes("/company/employee");
            for (Element element : elements) {
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                System.out.println(name + " = " + value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入
     */
    public static void write() {
        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            File xmlFile = new File("d://company.xml");
            Document document = new SAXReader().read(xmlFile);
            // 获取根节点
            Element root = document.getRootElement();
            // 动态添加 <employee name="xiaohong" value="小红"/>
            Element employee = root.addElement("employee");
            employee.addAttribute("name", "xiaohong");
            employee.addAttribute("value", "小红");
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("    ");// tab格
            outputFormat.setNewlines(true);// 换行
            fileOutputStream = new FileOutputStream(xmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
        }

    }

写入后XML格式:

<?xml version="1.0" encoding="UTF-8"?>

<company> 
    <employee name="zhangsan" value="张三"/>  
    <employee name="lisi" value="李四"/>  
    <employee name="wangwu" value="王五"/>  
    <employee name="xiaohong" value="小红"/>
</company>

 注:所需包 dom4j-1.6.1.jar、jaxen-1.1.1.jar

dom4j读写XML文件

标签:

原文地址:http://www.cnblogs.com/wenjian-li/p/4569218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!