the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


java简单读取XML(jdom方式)

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

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

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

.. code:: 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文件如下:

.. code:: 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>
- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈

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

其他分类: