【发布时间】:2012-11-14 22:16:30
【问题描述】:
C#新手问,所以如果问题很愚蠢或者答案很明显,可能是因为我不完全理解XmlDataSource是如何工作的。
给定以下 XML 文件“super-simple-xml.xml”(格式化以节省一些空间),
<items>
<item> <one id="ms">Microsoft</one> <two>MSFT</two> </item>
<item> <one id="in">Intel</one> <two>INTC</two> </item>
<item> <one id="de">Dell</one> <two>DELL</two> </item>
</items>
一个看起来像这样的中继器,
<asp:Repeater id="SuperSimple" runat="server" OnItemCommand="SuperSimple_ItemDataBound">
<HeaderTemplate>
<table border="1"><tr><th>Company</th><th>Symbol</th><th>Wrong</th></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Label Text=<%#XPath("one") %> runat="server" /></td>
<td><asp:CheckBox Text=<%#XPath("two") %> runat="server" id="symbol" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<asp:Button id="buttonOne" Text="Submit!" runat="server" />
</FooterTemplate>
</asp:Repeater>
和以下绑定XML:
private void Page_Load(object sender, EventArgs e)
{
XmlDataSource xmlSource = new XmlDataSource();
xmlSource.DataFile = "super-simple-xml.xml";
xmlSource.XPath = "items/item";
if (!IsPostBack) // Did this to prevent an error
{
SuperSimple.DataSource = xmlSource;
SuperSimple.DataBind();
}
}
如何将id 从每个 XML 条目中提取到类或变量中?
这里的想法是我在中继器中显示项目。我添加了复选框,因此我可以检查任何 <two> 条目,然后按提交。当它回发时,我想将选中的条目存储在我制作的课程中。获取<one> 和<two> 很容易,因为它们在Repeater 中有我可以参考的ID。但是 XML 中的 id 属性从未被调用过,所以我不知道如何找到它。我希望在传递数据时在类中有 id 以供参考。这可能吗,我该怎么做?
【问题讨论】:
-
为了澄清您的问题,您是要在“Page_Load”C# 方法中获取 id 属性的值,还是要在标记中提取 id 值,例如,就像你是“一”和“二”吗?
-
但是,最终不管怎样。 @Sean 解决了后一种情况,它似乎可行。我只是假设如果页面正在访问 XML 文件,我可以访问它而无需将其绑定到某些东西。
标签: c# asp.net xml data-binding asp.net-2.0