XML转换到数据表 [英] Convert Xml to DataTable
本文介绍了XML转换到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我想要插入,在DataTable的XML文件。
XML文件的格式如下图所示:
I have an XML file I want to insert that in a Datatable. The format of the xml file is like below:
<userid ID="37729">
<TestId ID="84" TimeRemaining="60" />
<QuestId ID="1">
<Answer1>
</Answer1>
<Answer2>B</Answer2>
<Answer3>
</Answer3>
<Answer4>
</Answer4>
</QuestId>
</userid>
现在我想插入数据表中象下面这样:
Now I want to insert that in a data table like below:
Question Id Answer1 Answer2 Answer3 Answer4
1 A D
2 B C
3 C
任何一个可以帮助我实现这一目标。
Can any one help me to achieve this.
推荐答案
我首先创建一个数据表
与您需要的列,然后通过填充LINQ到-XML。
I would first create a DataTable
with the columns that you require, then populate it via Linq-to-XML.
您可以使用一个选择查询来创建一个对象,再presents每一行,然后用标准的方法为每个项目创建的数据行...
You could use a Select query to create an object that represents each row, then use the standard approach for creating DataRows for each item ...
XDocument doc = XDocument.Load(yourXMLString);
var rows = doc.Descendants("QuestId").Select(el => new()
{
Answer1 = el.Element("Answer1").Value,
Answer2 = el.Element("Answer2").Value,
Answer3 = el.Element("Answer3").Value,
Answer4 = el.Element("Answer4").Value,
});
// iterate over the rows and add to DataTable ...
这篇关于XML转换到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文