【问题标题】:How to insert XML File NodeValue to SQL server database?如何将 XML 文件 NodeValue 插入 SQL Server 数据库?
【发布时间】:2013-03-18 14:36:49
【问题描述】:

我正在尝试将 XML 文件插入 SQL Server 数据库,但仍然不知道下面的代码有什么问题。

我的 XML 节点名称是:作者、标题、流派、价格、发布日期、描述。

通过获取上述节点名称,我想在我的数据库表中创建列,以便我可以将节点值插入到列中。

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

【问题讨论】:

    标签: java sql-server xml database insert


    【解决方案1】:

    可能是因为作者之前,行元素之后有一个空白子文本节点。例如:以下 XML 在 Row 和作者之间没有空格:

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

    但以下可能有(是的,空格和换行符通常很重要!)

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

    但这也取决于解析器配置

    【讨论】:

    • 哦,是的,gerrytan 我做了你说的改变,但现在打印为 null
    猜你喜欢
    • 2018-09-22
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2011-09-06
    相关资源
    最近更新 更多