如何将XML数据显示到ASP.Net gridview中?

时间:2011-11-08 19:39:16

标签: asp.net xml gridview

专家! 我是XML的新手。但是,webapp以XML格式收集数据,我必须在ASP.Net GridView中显示它(并启用编辑)。我需要你的帮助。

<?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>

1 个答案:

答案 0 :(得分:5)

我能想到将XML绑定到gridview的最简单方法是将xml加载到DataSet,然后将DataSet绑定到gridview:

StringReader sr= new StringReader(xml); 
DataSet ds = new DataSet();
ds.ReadXml(sr);

Gridview.DataSource=ds.Tables[1];
Gridview.DataBind();

执行ds.Tables[0]的原因是您的示例包含2组Answers,当您使用XML加载DataSet时,第一个DataTable将包含与您在答案上的答案集一样多的行XML,而第二个表将包含所有答案集中的所有行。

LinqPad显示的方式如下:

enter image description here

<强>更新

string xml=@"<?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>";
StringReader sr= new StringReader(xml); 
 DataSet ds = new DataSet();
 ds.ReadXml(sr);
 ds.Merge(ds,true);
 gridview.DataSoure=ds.Tables[1];
     gridview.DataBind();