我正在尝试将XML节点的内容绑定到下拉列表,但没有太大成功。
最初,整个XML文档绑定到转发器 - 这很好用,但是现在我需要根据“”节点中的子节点显示一个下拉列表,但是我得到了数据在根级别无效。第1行,dropDownList上DataBind()方法的第1位错误消息。
有人能告诉我,我做错了吗?
我正在使用的代码片段是:
IXPathNavigable x = (IXPathNavigable)e.Item.DataItem;
XPathNavigator questionNode = x.CreateNavigator();
string question = questionNode.SelectSingleNode("questionText").ToString();
//string title = xePage.SelectSingleNode("q").InnerText;
Literal questionText = (Literal)e.Item.FindControl("litQuestionText");
questionText.Text = question;
Panel iconDiv = (Panel)e.Item.FindControl("divIcon");
iconDiv.CssClass = string.Format("icon {0}", questionNode.SelectSingleNode("iconType"));
Panel sliderPanel = (Panel)e.Item.FindControl("pnlSlider");
DropDownList answerDropDown = (DropDownList)e.Item.FindControl("ddlAnswer");
TextBox answerText = (TextBox)e.Item.FindControl("txtAnswer");
switch (questionNode.SelectSingleNode("answerType").ToString())
{
case "d":
sliderPanel.Visible = false;
answerText.Visible = false;
answerDropDown.Visible = true;
XmlDataSource answersList = new XmlDataSource();
answersList.Data = questionNode.Select("answers").ToString();
Response.Write(answersList.ToString());
//XPathNodeIterator answers = questionNode.Select("answers");
//answers.AsQueryable();
answersList.ID = questionNode.SelectSingleNode("questionId").ToString();
answerDropDown.DataSource = answersList;
answerDropDown.DataTextField = "@display";
answerDropDown.DataValueField = "@value";
answerDropDown.DataBind();
break;
case "s":
sliderPanel.Visible = true;
answerText.Visible = false;
answerDropDown.Visible = false;
break;
case "t":
sliderPanel.Visible = false;
answerText.Visible = true;
answerDropDown.Visible = false;
break;
我正在使用的XML是:
<questions>
<question>
<questionId>1</questionId>
<questionText>Question here?</questionText>
<iconType>a</iconType>
<answerType>d</answerType>
<answers>
<answer value="-3" display="Extremely badly"/>
<answer value="-2" display="Very badly"/>
<answer value="-1" display="Quite badly"/>
<answer value="0" display="Neither well nor badly"/>
<answer value="1" display="Quite well"/>
<answer value="2" display="Very well"/>
<answer value="3" display="Extremely well"/>
</answers>
</question>
<question>
<questionId>1</questionId>
<questionText>Question again here?</questionText>
<iconType>b</iconType>
<answerType>s</answerType>
<answers/>
</question>
</questions>
答案 0 :(得分:0)
显然我错过了xml文档顶部的xml声明。聪明。
但是,实现此功能的最佳方法是为问题和答案创建问卷调查对象和类,然后通过反序列化将XML转换为类。然后,您可以将调查问卷的问题绑定到下拉列表中,在完成创建对象所需的初始工作后,它基本上可以更好,更轻松地完成工作。