简体   繁体   中英

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.

I have an XML file, Bricks.xml, with the structure :

<?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). I would like to be able to take the input from txtName.text and display it in my grid view. I currently have this all set up in panels with one panel for the txtName and btnSearch, which is always visible. 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." I would think it would be possible to get read of that, and just reload the gridview that is already displayed.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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