RadioButtonList inside Repeater bound to XmlDataSo

2019-09-12 01:23发布

问题:

I have the following XML:

<questions>
<question text="This is a test question?">
<answer value="Yes">
 <requirement articleId="2899"/>
</answer>
<answer value="No">
  <requirement articleId="2899"/>
</answer>
</question>
</questions>

And I have the following markup in my ASPX page:

<asp:Repeater ID="rptQuestions" runat="server" DataSourceID="xdsQuestions">
<ItemTemplate>
    <p>
        <asp:Label ID="lblText" runat="server" Text='<%# Eval("text") %>' />
    </p>
    <div>
        <asp:RadioButtonList ID="rblAnswers" runat="server" RepeatDirection="Horizontal"
            RepeatLayout="Flow" AutoPostBack="true" OnSelectedIndexChanged="rblAnswers_SelectedIndexChanged"
            DataSource='<%# XPathSelect("answer") %>' DataTextField="value" DataValueField="value" />
    </div>
</ItemTemplate>
</asp:Repeater>
<asp:XmlDataSource ID="xdsQuestions" runat="server" DataFile="~/App_Data/QA.xml"
XPath="./questions/question" />

So far the only way I've been able to get this to work is to move the 'value' attribute of the 'answer' node into the element (like this: <value>Yes</value>) and bind to the 'InnerText' property of the 'answer' node, since XPathSelect is returning a collection of XmlElement. This is not how I want to go about it, because if any of the other child nodes of 'answer' (such as the 'requirement' node) also has InnerText, it gets concatenated along with 'value' in the ListItems of the RadioButtonList.

Any suggestions on how to bind my RadioButtonList without changing the XML?

回答1:

Inside your RadioButtonList, change your DataSource to the following:

DataSource='<%# XPathSelect("answer/@value") %>'