c# - 在 asp.net 中使用带项目符号列表的 xml

标签 c# asp.net .net xml bulletedlist

我正在尝试创建项目符号列表并使用 xml 文件 (Kategoriler.xml) 作为数据源。这是我的 xml 代码:

<bookstore>
 <book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
 </book>
</bookstore>

页面设计:

<asp:BulletedList ID="BulletedList2" runat="server" BulletStyle="Numbered" DataSourceID="XmlDataSource1">
</asp:BulletedList>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Kategoriler.xml"></asp:XmlDataSource>

当我运行代码时,我看到如下列表:

1.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor
2.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor
3.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor
4.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor

我不知道我做错了什么。 感谢您的宝贵时间。

最佳答案

您必须在 BulletedList 中指定 DataTextFieldDataValueField 属性:-

<asp:BulletedList ID="BulletedList2" runat="server" BulletStyle="Numbered" 
     DataSourceID="XmlDataSource1" DataTextField="author" DataValueField="year" >
</asp:BulletedList>

更新:

@Michael 是正确的 XmlDataSource 不适用于 xml 节点的值,而只能用于属性,因此您必须像这样修改 XML:-

<bookstore>
 <book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author name="Giada De Laurentiis" year="2005"></author>
  <year></year>
  <price>30.00</price>
 </book>
</bookstore>

然后,您必须像这样指定 XPath 属性:-

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Kategoriler.xml" 
  XPath="/bookstore/book/author"></asp:XmlDataSource>

然后,相应地更改 BulletedList 属性:-

DataTextField="name" DataValueField="year"

但是,实际上您可能无法更改 XML 本身,因此您可以在代码隐藏中读取此 XML,然后以编程方式绑定(bind) BulletedList。

更新 2:

正如我所说,根据 XMLDataSource 行为更改您的 XML 文件是不切实际的,您也可以使用 LINQ-to-XML 来查询您的 XML 文件并绑定(bind)它像这样:-

XDocument xdoc = XDocument.Load(@"YourXMLFilePath");
var XMLdata = xdoc.Descendants("book")
                   //Optional Filter
                   .Where(x => (string)x.Attribute("category") == "cooking") 
                   .Select(x => new
                           {
                              AuthorName = (string)x.Element("author"),
                              Year = (string)x.Element("year")
                           });

最后,您可以像这样绑定(bind)数据:-

BulletedList2.DataSource = XMLdata;
BulletedList2.DataValueField = "Year";
BulletedList2.DataTextField = "AuthorName";
BulletedList2.DataBind();

关于c# - 在 asp.net 中使用带项目符号列表的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33037390/

相关文章:

c# - 在 System.IO.Directory.GetFiles() 中排除文件扩展名

c# - 超链接控件 vs 链接按钮 vs ImageButton vs ASP.NET 中的按钮控件

c# - CancellationTokens 可以跨 AppDomains 使用吗

c# - Convert.FromBase64String(...) 抛出 FormatException

c# - 如何更改 Windows 控件的 `All Desired` 属性?

c# - 如何以编程方式为 IIS 添加通配符筛选器?

c# - VideoSourcePlayer 控件中视频源的同步声音播放

c# - 强制 EF ApplicationUser 加载导航属性

c# - ASP.Net C# 帮助器,返回一个数组

javascript - 在 GridView DevExpress 中添加操作