将 Xml 转换为数据表 [英] Convert Xml to DataTable
本文介绍了将 Xml 转换为数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 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.
推荐答案
我将首先使用您需要的列创建一个 DataTable
,然后通过 Linq-to-XML 填充它.
I would first create a DataTable
with the columns that you require, then populate it via Linq-to-XML.
您可以使用 Select 查询来创建代表每一行的对象,然后使用标准方法为每个项目创建 DataRows ...
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 ...
class Quest
{
public string Answer1;
public string Answer2;
public string Answer3;
public string Answer4;
}
public static void Main()
{
var doc = XDocument.Load("filename.xml");
var rows = doc.Descendants("QuestId").Select(el => new Quest
{
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屋!
查看全文