import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLParser {
public void getAllUserNames(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "
+ docEle.getNodeName());
NodeList studentList = docEle.getElementsByTagName("student");
// Print total student elements in document
System.out
.println("Total students: " + studentList.getLength());
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out
.println("=====================");
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("C:/Users/rasika_patil01/Desktop/205_008_JAXBTesterOld/Student.xml");
}
}使用下面的代码,我会得到如下输出:
输出:文档的根元素:学生
学生总数:4人
姓名:约翰·格雷:B
年龄: 12岁
姓名:玛丽·格雷:A
年龄: 11岁
姓名:西蒙·格雷:A
年龄: 18岁
姓名: Rasika年级: A+年龄: 23岁
我想将上面的输出存储到MySQL中。有人能帮帮忙吗?
发布于 2016-02-16 16:02:50
MysqlDataSource dataSource =新建MysqlDataSource();dataSource.setUser(用户);dataSource.setPassword(密码);dataSource.setServerName(服务器);dataSource.setDatabaseName(数据库);Connection conn = dataSource.getConnection();PreparedStatement stmt = conn.prepareStatement("INSERT INTO table (name,grade,age) VALUES (?,?,?)");遍历XML时的...then : stmt.setString(1,名称);stmt.setString(2,等级);stmt.setString(3,年龄);stmt.execute();结束: stmt.close();conn.commit();conn.close()
使用实际的数据库连接参数,以及数据库表名、列名、列类型。
https://stackoverflow.com/questions/35424871
复制相似问题