码迷,mamicode.com
首页 > 编程语言 > 详细

java读取xml文件

时间:2015-09-04 12:39:44      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:java xml

需要引入一个第三方jar包:dom4j

package test;

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

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Test {

    public static void main(String[] args) {
        SAXReader reader = new SAXReader();
        String realPathString;
        try {
            // 获取文件真实路径
            realPathString = new File("").getCanonicalPath() + "/dbconfig.xml";
            System.out.println("[path:] " + realPathString);
            // 读取文件
            Document document = reader.read(realPathString);
            // 获取 components根节点
            Element components = document.getRootElement();
            // 遍历 component
            Element component;
            for (Iterator i = components.elementIterator("component"); i.hasNext();) {
                component = (Element) i.next();
                // 获取name属性
                Attribute name = component.attribute("name");
                System.out.println("[name:]" + name.getText());
                // 获取class属性
                Attribute cls = component.attribute("class");
                System.out.println("[class:]" + cls.getText());
                // 遍历当前component的所有属性
                for (Iterator ite = component.elementIterator("property"); ite.hasNext();) {
                    Element property = (Element) ite.next();
                    // 获取该property的name属性以及value
                    Attribute pname = property.attribute("name");
                    System.out.println("[" + pname.getText() + "]:" + property.getText().trim());
                }
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}

dbconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<components>
    <component name="DataSource" class="test.XDataSource">
        <property name="driverClassName">"com.mysql.jdbc.Driver"</property>
        <property name="URL">
            "jdbc:mysql://127.0.0.1:3306/mytestdb"
        </property>
        <property name="user">"root"</property>
        <property name="password">""</property>
    </component>
</components>


java读取xml文件

标签:java xml

原文地址:http://jishunote.blog.51cto.com/4643968/1691279

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