利用JDOM操纵XML文件(数据库连接)

来源:互联网 发布:学java要学数据库吗? 编辑:程序博客网 时间:2024/06/05 15:17

利用JDOM操纵XML文件(数据库连接)

import java.io.IOException;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.*;
import java.util.*;
import org.jdom.output.*;
import java.io.*;

public class TestJDom {
    public TestJDom() {
    }

    public static void main(String[] args) throws Exception {
        TestJDom d = new TestJDom();
        d.writeDb();
    }

    public void writeDb() throws IOException {
        Document doc = new Document();
        Element root = new Element("数据库");

        Element driver = new Element("driver");
        driver.setText("sun.jdbc.odbc.JdbcOdbcDrver");
        Element uri = new Element("uri");
        uri.setText("jdbc:odbc:db");
        Element userName = new Element("userName");
        userName.setText("sa");
        Element passWord = new Element("passWord");
        passWord.setText("sa");

        root.addContent(driver);
        root.addContent(uri);
        root.addContent(userName);
        root.addContent(passWord);

        doc.setRootElement(root);

        XMLOutputter out = new XMLOutputter();
        Format format = Format.getPrettyFormat();
        format.setEncoding("GB2312");
        out.setFormat(format);
        out.output(doc,new FileOutputStream("c:/db.xml"));
    }

    public void readJdom() throws Exception {
        SAXBuilder sb = new SAXBuilder();
        Document doc = sb.build("c:/tt.xml");
        Element root = doc.getRootElement();
        List list = root.getChildren();

        System.out.println(root.getChild("student").getValue());


        for (int i = 0; i < list.size(); i++) {
            Element ele = (Element)list.get(i);
            System.out.println(ele.getName()+"  "+ele.getValue());
        }

    }

}

原创粉丝点击