如何将XML文件NodeValue插入到SQL Server数据库?
问题描述:
我想将XML文件插入到SQL Server数据库,但仍然不知道我的代码在下面出了什么问题。如何将XML文件NodeValue插入到SQL Server数据库?
我的XML节点名称是:author,title,genre,price,publish_date,description。
通过获取上述节点名称,我想在我的数据库表中创建列,以便我可以将节点值插入到列中。
我的XML文件的样子:
<?xml version="1.0"?>
<Results>
<Row>
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</Row>
<Row>
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
.
.
.
.
.
</Row>
</Results>
Java代码插入到数据库:
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;user=joy\studentsdatabaseName=EMPLOYEEintegratedSecurity=t rue;");
Statement st=con.createStatement();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("d:/books.xml");
NodeList n1= doc.getElementsByTagName("Row");
for(int i=0;i<n1.getLength();i++){
String st1= n1.item(i).getFirstChild().getNodeValue();
System.out.println(st1); // i dont know why it doesnt print anything ?
st.executeUpdate("insert into checktbl(sub)values('"+st1+"')");
}
}
catch(Exception e){
e.printStackTrace();
}
答
也许是因为有笔者之前空格子文本节点,行元素之后。例如:下面的XML没有行和作者之间的空白:
<Row><author>blah</author></Row>
但以下可能(是空格和换行往往计数!)
<Row>
<author>blah</author></Row>
但是,这可能取决于解析器配置太
哦是的gerrytan我做了你说的改变,但它现在打印null – stom 2013-04-01 05:37:42