2013-03-28 83 views
1

我想將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(); 
} 

回答

0

也許是因爲有筆者之前空格子文本節點,行元素之後。例如:下面的XML沒有行和作者之間的空白:

<Row><author>blah</author></Row> 

但以下可能(是空格和換行往往計數!)

<Row> 
    <author>blah</author></Row> 

但是,這可能取決於解析器配置太

+0

哦是的gerrytan我做了你說的改變,但它現在打印null – stom 2013-04-01 05:37:42

相關問題