从 xml 文件中检索数据并插入到数据库表中 [英] Retrieve data from xml file and insert into database table

查看:23
本文介绍了从 xml 文件中检索数据并插入到数据库表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 c# .net 1.1 和 SQL Server 2000....

I am using c# .net 1.1 and SQL Server 2000....

我想从 xml 文件中检索数据并将该数据存储到数据库表中.

I want to retrive data from an xml file and store that data into the database table.

XML 文件:

<information>
  <data>
    <id="1"></id>
    <name>peter</name>
    <age>25</age>
  </data>
</information>

我的数据库表是

id int,
name varchar(100),
age int

推荐答案

首先 - 您的 XML 无效:

First off - your XML is invalid:

<data>
    <id="1"></id>

这不是一个有效的 XML 结构 - 它应该是什么??

This is not a valid XML construct - what should it be??

数据节点上的ID"属性?

An "ID" attribute on the data node? <data id="1">

一个带有值的ID"元素?1

An "ID" element with the value inside? <data><id>1</id>

有很多方法可以做到这一点 - 完全取决于您的情况:

There's a ton of ways you can do this - totally depends on your situation:

  • 创建一个 XML 模式,以便您可以将此 XML 反序列化为 .NET 对象 - 如果您有大量这些文件要导入,则效果最佳

  • create a XML schema so you can deserialize this XML into a .NET object - works best if you have tons of those files to import

如果您使用的是 .NET 3.5 及更高版本,请使用 Linq-to-XML

use Linq-to-XML if you're on .NET 3.5 and up

使用传统的 XML 文档处理

use traditional XML document processing

如果您使用传统的 XML 文档处理,那么在您的文件相对较小的情况下效果最佳(因为它将整个文件加载到内存中).在这种情况下,您可以执行以下操作:

If you use traditional XML document processing, this works best if your files are relatively small (since it loads the entire file into memory). In that case, you could do something like:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("yourfilename.xml");

XmlNodeList dataNodes = xmlDoc.SelectNodes("/information/data");

foreach(XmlNode node in dataNodes)
{
    int id = Convert.ToInt32(node.SelectSingleNode("id").InnerText);
    string name = node.SelectSingleNode("name").InnerText;
    int age = Convert.ToInt32(node.SelectSingleNode("age").InnerText);

    // insert into database, e.g. using SqlCommand or whatever
}

至于插入数据库 - 您可以使用存储过程或 SqlCommand 中的 SQL 语句 - 完全由您决定.一旦您获得了三项信息(id、姓名、年龄),您就可以随心所欲地处理这些信息.

As for inserting into a database - you can use a stored procedure, or a SQL statement in a SqlCommand - totally up to you. Once you have the three bits of information (id, name, age), you can do with those whatever you like.

警告语:这包括无错误检查!如果 <data> 节点不完整或子节点名称错误,这将崩溃 - 您也需要提供一些错误检查!(为简单起见省略)

Word of warning also: this includes no error checking whatsoever! If a <data> node should be incomplete or a sub node has a wrong name, this will crash - you need to provide some error checks, too! (left out for simplicity)

马克

这篇关于从 xml 文件中检索数据并插入到数据库表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆