利用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());
}
}
}
本文展示了一个使用Java JDOM库读写XML文件的具体实例。包括创建XML文档、添加元素及属性、设置文本内容,并将文档保存到XML文件中。此外,还提供了从XML文件中读取数据的方法。
1万+

被折叠的 条评论
为什么被折叠?



