使用C#LINQ搜索XML文件
我目前正在复习一些使用LINQ和XML与ASP.NET C#结合使用的教程。我想创建一个搜索页面,该页面读取xml文件,并在单击按钮后在网格视图中返回结果 这是我试图搜索的XML文件:使用C#LINQ搜索XML文件,c#,asp.net,xml,linq,C#,Asp.net,Xml,Linq,我目前正在复习一些使用LINQ和XML与ASP.NET C#结合使用的教程。我想创建一个搜索页面,该页面读取xml文件,并在单击按钮后在网格视图中返回结果 这是我试图搜索的XML文件: <?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Develop
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
…我的问题是,如何在代码的后端实现id:searchtxt?此外,在完成任务时,我是否走上了正确的道路、设置和语法 识别目录子体
并迭代图书元素
var term = "rain";
var query = from element in document
.Descendants("catalog")
.Elements("book")
let book = new
{
id = element.Attribute("id").Value,
author = element.Element("author").Value,
title = element.Element("title").Value,
genre = element.Element("genre").Value
}
where book.author.ToLower().Contains(term)
|| book.title.ToLower().Contains(term)
|| book.genre.ToLower().Contains(term)
select book;
那会给你
id|author|title|genre
bk102|Ralls, Kim|Midnight Rain|Fantasy
您不需要在
Select
和OrderBy
之间使用ToList
,老实说,我建议不要养成使用ToList
的习惯,这样您就可以使用ForEach
。相反,只需将结果分配给一个变量,并使用常规的foreach
(这样可以节省创建不需要的中间列表的时间)使用xdoc.substands(“book”)
not catalog尝试您的代码谢谢您的建议。。当我单击按钮时,我得到一个对象引用,该引用未设置为下面一行的对象错误实例:xdoc.subjects(“book”)。Select(p=>new…我不确定如何绑定searchtxt(文本框的ID放在后端。你有什么建议吗?…但是,文本框的ID值:searchtxt,我如何将其绑定到后端代码中?我相信这就是在你的代码中生成对象引用错误的原因,你将作者和类型作为一个属性,而它最有可能是元素r将搜索值传递给底层的点击处理程序,这对于asp.net来说是非常特殊的,我已经很久没有接触过这些东西了,但是我想命令参数应该可以做到这一点
protected void search_btn_Click(object sender, EventArgs e)
{
//1 .create a reference of XDocument
XDocument xdoc = XDocument.Load("database\\books.xml");
xdoc.Descendants("book").Select(p => new
{
author = p.Attribute("author").Value,
title = p.Element("title").Value,
genre = p.Attribute("genre").Value
}) .OrderBy(p => p.author).ToList().ForEach(p =>
{
gvSearch.DataSource = xdoc;
gvSearch.DataBind();
});
}
var term = "rain";
var query = from element in document
.Descendants("catalog")
.Elements("book")
let book = new
{
id = element.Attribute("id").Value,
author = element.Element("author").Value,
title = element.Element("title").Value,
genre = element.Element("genre").Value
}
where book.author.ToLower().Contains(term)
|| book.title.ToLower().Contains(term)
|| book.genre.ToLower().Contains(term)
select book;
id|author|title|genre
bk102|Ralls, Kim|Midnight Rain|Fantasy