如何将XML文件转换为DataSource?

时间:2011-11-09 22:26:52

标签: asp.net xml database

首先,我想告诉您,我之前从未使用过XML作为数据源。

我有一个名为“answers.xml”的XML文件,我需要连接gridview,formview等...

<?xml version="1.0"?>
<Answers>  
<AnswerSet>
    <Answer questionId="MRN">4444</Answer> 
    <Answer questionId="FName">test</Answer> 
    <Answer questionId="LName">patient</Answer> 
    <Answer questionId="AddressPt">blah blah</Answer> 
    <Answer questionId="Governorate">xxxx</Answer> 
    <Answer questionId="InitialCSF">Negative</Answer> 
    <Answer questionId="Diagnosis"></Answer> 
    <Answer questionId="Description"> </Answer>   
</AnswerSet>   
<AnswerSet> 
    <Answer questionId="MRN">1</Answer> 
    <Answer questionId="FName">1</Answer> 
    <Answer questionId="LName">1</Answer> 
    <Answer questionId="AddressPt">1</Answer> 
    <Answer questionId="InitialCSF">Positive</Answer> 
    <Answer questionId="Diagnosis">dx</Answer> 
    <Answer questionId="Description"> </Answer>   
</AnswerSet>
</Answers>

我需要一种方法来使用.NET

更改xml文件中的数据(编辑/删除)

2 个答案:

答案 0 :(得分:3)

如果您不想使用XmlDataSource控件,还可以使用LINQ to XML从文件中创建数据源对象:

XDocument doc = XDocument.Load("somefile.xml");

var results = from answer in doc.Descendants("Answer")
              select new
              {
                  Question = answer.Attribute("questionId").Value,
                  Answer = answer.Value
              };

GridView1.DataSource = results;
GridView1.DataBind();

答案 1 :(得分:2)

System.Web.UI.WebControls.XmlDataSource类将返回给定XML文件的ASP.NET DataSource。给定的链接包括示例代码和演练。

请注意,如果必须使用XML属性作为键,则XPath expressin将包含Answer[@MRN]之类的内容。