繁体   English   中英

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

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

在整个Web开发方面还算是新事物,一个早晨的Google搜索和通过堆栈溢出的浏览为我指明了正确的方向,但是我仍然遇到问题。

我有一个XML文件Bricks.xml,其结构为:

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

我有一个文本框(txtName)和一个按钮(btnSearch)。 我希望能够从txtName.text获取输入并将其显示在我的网格视图中。 我目前在面板中设置了所有这些内容,其中一个面板用于txtName和btnSearch,该面板始终可见。 我有另一个带有网格视图的面板,该面板可提取整个XML文件,最后还有另一个面板,它具有与我打算用作“搜索结果”的网格视图相同的网格。 我认为有可能读到它,然后重新加载已经显示的gridview。

因此,您需要执行类似的操作以搜索节点以找到具有特定名称的节点。 然后,您只需要对结果做任何事情即可...

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