public static void main(String[] args) {
Connection con = ConDB.Con();
PreparedStatement pst = null;
ResultSet rs = null;
String colName;
try {
pst = con.prepareStatement("SELECT * FROM master");
rs = pst.executeQuery();
Document document = new Document(new Element("根元素")); //创建文档,并设根元素
ResultSetMetaData rsmd = rs.getMetaData(); //获取字段名,返回ResultSetMetaData对像
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
Element element0 = new Element("users"); //创建元素 生成JDOM树
document.getRootElement().addContent(element0);
// Element element2 = new Element("userphone");
// element0.addContent(element2);
for (int i = 1; i <= numberOfColumns; i++) {
try {
colName = new String(rs.getString(i));
//构造元素节点和文本节点
Element element = new Element(rsmd.getColumnName(i)).setText(colName);
element0.addContent(element);
} catch (Exception ex1) {
}
}
}
//org.jdom.output.XMLOutputter
XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
try {
//生成XML文件路径
outp.output(document,new FileOutputStream("aa.xml"));
} catch (IOException ex2) {
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
然后再用以下代码读取XML里面的元素
public static void main(String[] args) {
Connection con = ConDB.Con();
PreparedStatement pst = null;
try {
BufferedReader br = new BufferedReader(new FileReader(
"aaa.xml"));
DOMParser parser = new DOMParser();
parser.parse(new InputSource(br));
org.w3c.dom.Document doc = parser.getDocument();
org.w3c.dom.NodeList nl = doc.getElementsByTagName("*");
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
System.out.println(n.getNodeName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}