简体   繁体   English

通过C#中的LINQ在XML文件中按名称搜索并在GridView中显示

[英]Searching by Name in XML file through LINQ in C# and displaying in GridView

Pretty new at this whole web development thing and a morning of google search and looking through stack overflow has pointed me in the right direction, but I'm still having issues. 在整个Web开发方面还算是新事物,一个早晨的Google搜索和通过堆栈溢出的浏览为我指明了正确的方向,但是我仍然遇到问题。

I have an XML file, Bricks.xml, with the structure : 我有一个XML文件Bricks.xml,其结构为:

<?xml version="1.0"?>
<Links>
    <Table1
        Name="Bob Smith"
        Text="GO TEAM!!!"
        Location="Tennis Court"
    />
</Links>

I have a text box, (txtName) and a Button (btnSearch). 我有一个文本框(txtName)和一个按钮(btnSearch)。 I would like to be able to take the input from txtName.text and display it in my grid view. 我希望能够从txtName.text获取输入并将其显示在我的网格视图中。 I currently have this all set up in panels with one panel for the txtName and btnSearch, which is always visible. 我目前在面板中设置了所有这些内容,其中一个面板用于txtName和btnSearch,该面板始终可见。 I have another panel with the grid view that pulls the whole XML file, and finally a third panel with the same grid view which I intended to use as the "search results." 我有另一个带有网格视图的面板,该面板可提取整个XML文件,最后还有另一个面板,它具有与我打算用作“搜索结果”的网格视图相同的网格。 I would think it would be possible to get read of that, and just reload the gridview that is already displayed. 我认为有可能读到它,然后重新加载已经显示的gridview。

So you would want to do something like this to search through the nodes to find one that has a specific name. 因此,您需要执行类似的操作以搜索节点以找到具有特定名称的节点。 Then you just need to do whatever you want with the results ... 然后,您只需要对结果做任何事情即可...

string nameToSearch = "Bob";
string rawXML = null;

using (var stream = new StreamReader(File.OpenRead("<YOUR_FILE_PATH>")))
{
    rawXML = stream.ReadToEnd();
}

if (rawXML != null)
{
    XDocument doc = XDocument.Parse(rawXML);
    XElement foundNode = doc.Descendants("Table1").Where(n => n.Attribute("Name").Value.Contains(nameToSearch)).FirstOrDefault();

    if (foundNode != null)
    {
        string name     = foundNode.Attribute("Name").Value;
        string text     = foundNode.Attribute("Text").Value;
        string location = foundNode.Attribute("Location").Value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM