the5fire的技术博客

关注python、vim、linux、web开发和互联网--life is short, we need python.


java简单读取XML(jdom方式)

作者:the5fire | 标签:       | 发布:2010-12-04 5:56 p.m. | 阅读量: 3584, 3581

首先你需要从http://jdom.org/dist/binary/jdom-1.1.1.zip下载jdom包,然后在eclipse中导入。

建立一个java类,用以下代码:

import org.jdom.output.*;
import org.jdom.input.*;
import org.jdom.*;

import java.io.*;
import java.util.*;

public class XmlConfigReader {
    public static void main(String[] args) {
        SAXBuilder builder = new SAXBuilder();
        Document read_doc;
        try {
            read_doc = builder.build("src//sys-conf.xml");
            Element stu = read_doc.getRootElement();
            List list = stu.getChildren("db-info");
            for(int i = 0;i < list.size();i++)
            {
                Element e = (Element)list.get(i);
                String str_name = e.getChildText("driver-name");
                String str_url = e.getChildText("url");
                System.out.println("-----------------------");
                System.out.println("driver-name:" + str_name);
                System.out.println("url:" + str_url);
                System.out.println("------------------------------");
                System.out.println();
            }
        } catch (JDOMException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
}

sys-conf.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <db-info>
        <driver-name>com.mysql.jdbc.Driver</driver-name>
        <url>jdbc:mysql://192.168.1.100/drp1?user=root&amp;password=root</url>
    </db-info>
</config>

----EOF-----

扫码关注,或者搜索微信公众号:码农悟凡

【上一篇】 XML,XSL,DTD,SCHEMA
【下一篇】 常用的正则表达式集合

其他分类: