将数据从 xml 导入数据库
我想通过 xml 文件将数据导入到我的数据库中:
var doc = XDocument.Load(XMLFile);
var nodes = from e in doc.Descendants("Person")
where e.Element("PersonID").Value == "1"
select e;
person 表与节点中的数据具有相同的结构。使用实体框架/linq-to-xml方便吗?
i would like to import data into my database through an xml file:
var doc = XDocument.Load(XMLFile);
var nodes = from e in doc.Descendants("Person")
where e.Element("PersonID").Value == "1"
select e;
The person table has same structure as the data from nodes. Is it handy to use entity framework/linq-to-xml ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 XML 的格式正确 - 即如果它使用与
DataSet
使用的相同格式 - 您只需使用DataSet.ReadXml()
读取它,然后使用所有用于将数据插入数据库的普通 ADO 工具。不过,如果您首先实际上从DataSet
生成了 XML,因此拥有可供ReadXml
使用的架构,这确实很有帮助,因为这可以解析大量数据否则您必须显式处理的类型转换问题。If the XML's format is right - i.e. if it uses the same format that the
DataSet
uses - you can just read it usingDataSet.ReadXml()
and then use all of the normal ADO tools for inserting the data into your database. Though it really helps if you've actually generated the XML from aDataSet
in the first place and thus have a schema forReadXml
to use, because that resolves a lot of data type conversion issues that you'd otherwise have to take care of explicitly.我不知道你所说的“方便”是什么意思,但这当然是可能的。
如果架构匹配,您可以非常轻松地将
XElement
节点映射到 LINQtoSQL/EF 生成的对象。您上面的代码应该会产生一个带有
XName
“Person”的IEnumerable
,因此从那里您只需要执行类似的操作
您将需要执行一些转换,例如对于某些数据类型,使用
int.Parse()
,因为XElement.Value
返回一个字符串。然后,为了将其保存到数据库,我们假设
MyDataContext
是 LINQ to SQL 生成的DataContext
对象,其属性People
是一个表<人员>
。您所要做的就是:I don't know what you mean by "handy", but it is certainly possible.
You can map the
XElement
nodes to your LINQtoSQL/EF-generated objects quite easily, if the schemas match.Your above code should result in an
IEnumerable<XElement>
with theXName
"Person",so from there you just need to do something like
You will need to do some conversions like the
int.Parse()
for some datatypes, becauseXElement.Value
returns a string.Then to save it to the database, let's assume
MyDataContext
is a LINQ to SQL generatedDataContext
object with a propertyPeople
that is aTable<Person>
. All you have to do is: