如何从XML文件中搜索数据?

时间:2016-08-02 11:31:20

标签: c# asp.net xml

正在 ASP.NET 中开发搜索应用程序。我将数据存储在 XML 文件中。当我在文本框中搜索数据并单击“提交”按钮时,它应搜索完整的XML文件并检索数据。 这是示例xml数据......

<college>
    <students>
        <student>
            <name>harish</name>
            <id>002</id>
        </student>
        <student>
            <name>vamshi</name>
            <id>003</id>
        </student>
    </students>
</college>

现在当我用这种形式搜索&#34; vamshi的详细信息&#34;在文本框中,它应该显示vamshi详细信息。我可以这样做..

3 个答案:

答案 0 :(得分:0)

您可以使用自定义文本搜索过程来搜索xml,就像它是文本文件一样。但是,我不建议这样做。

我认为最好的解决方案是将xml文件转储到程序中的类college中。

要做到这一点:

  1. 设置college类和student类以匹配xml文件。例如。大学应该有List<student>,学生应该有idname。可能是两个字符串,因为你有前导零。
  2. Download and add this XML helper class to your project

  3. 将您的大学xml转储到您创建的课程中:

    College c = new College();        
    c = XmlHelper.FromXmlFile<College>(@"/path/to/XML/File");
    
  4. 您的College课程现在填充了xml中的数据,您可以执行所需的搜索操作。
  5. 希望这有帮助!

答案 1 :(得分:0)

为了实现您的目标,首先,您需要将xml文件解析为C#对象。通过这样做,您可以将xml文件加载到内存中。

然后使用内置的C#xml解析器函数通过给定的信息跟踪xml节点,在您的情况下是学生对象的“Name”属性。

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
XmlNode node = doc.SelectSingleNode("//Student/Name/");
// node.Value contains "test@ABC.com"

答案 2 :(得分:0)

我最近写了一些可能对你有帮助的东西,它是用 C# 编写的:

        public string GetConnectionString(string nodeName, string xmlFile)
        {
            XmlDocument xmLDocument = new XmlDocument();
            xmLDocument.Load(xmlFile);
            XmlElement root = xmLDocument.DocumentElement;
            foreach (XmlNode childNode in root.ChildNodes) 
            {
                return RecurseNodeTree(childNode, nodeName);
            }
            return null;
        }

        private string RecurseNodeTree(XmlNode xmlNode, string nodeName) 
        {
            if (xmlNode.Name == nodeName) 
            {
                return xmlNode.InnerText;
            }

            if (xmlNode.HasChildNodes) 
            {
                foreach (XmlNode childNode in xmlNode.ChildNodes) 
                {
                    if (xmlNode.NextSibling != null)
                    {
                        return RecurseNodeTree(xmlNode.NextSibling, nodeName);
                    }

                    return RecurseNodeTree(childNode, nodeName);
                }
            }

            if (xmlNode.NextSibling != null)
            {
                return RecurseNodeTree(xmlNode.NextSibling, nodeName);
            }

            return null;
        }

这应该可以解决您或其他任何人的问题。

相关问题