通过不区分大小写的子字符串搜索在XML中查找节点

时间:2019-03-02 03:54:21

标签: c# .net xml

我正在读取XML文件,并要求用户输入要搜索的航空公司的名称,方法是将XML保留为大写,条件通过并显示所需的信息,但是将信息保留在小写和小写或大写,不返回任何内容。

public class XMLReader
    {
        public XMLReader()
        {
        }
        //Fin de metdo leerXML.
        public void leerXML()
        {
            Console.WriteLine("Enter the airline you wish to search: ");
            string name;
            name = Console.ReadLine().ToUpper();

            if (!String.IsNullOrEmpty(name))
            {
                XElement info = XElement.Load(
                  @"C:\Users\thoma\Documents\Visual Studio 2019\Backup Files\data.xml");

                var airlines = info.XPathSelectElements("aerolinea");
                foreach (XElement el in airlines)
                {
                    if (!String.IsNullOrEmpty(el.Element("nombre").Value) && 
                      ((string)el.Element("nombre").Value).IndexOf(name) >= 0)
                    {
                        Console.WriteLine((string)el.Element("origen").Value);
                        Console.WriteLine((string)el.Element("destino").Value);
                        Console.WriteLine((string)el.Element("fecha").Value);
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            XMLReader xmlReader = new XMLReader();
            xmlReader.leerXML();
            Console.ReadLine();
        }
    }

这是XML

<?xml version="1.0" encoding="iso-8859-1"?>
<aerolineas>
    <aerolinea id="01">
        <nombre>VIVA COLOMBIA</nombre>
        <origen>BOG</origen>
        <destino>MDE</destino>
        <fecha>01/03/2019</fecha>
    </aerolinea>
    <aerolinea id="02">
        <nombre>HK Express</nombre>
        <origen>BOG</origen>
        <destino>CTG</destino>
        <fecha>01/06/2019</fecha>
    </aerolinea>
    <aerolinea id="03">
        <nombre>Volotea</nombre>
        <origen>PEI</origen>
        <destino>BOG</destino>
        <fecha>01/09/2019</fecha>
    </aerolinea>
    <aerolinea id="04">
        <nombre>Vueling</nombre>
        <origen>MDE</origen>
        <destino>BOG</destino>
        <fecha>01/12/2019</fecha>
    </aerolinea>
</aerolineas>

1 个答案:

答案 0 :(得分:1)

更改

 name = Console.ReadLine().ToUpper();

 name = Console.ReadLine();

您的原始代码正在读取用户输入,然后将其更改为全部大写,然后再将其存储在“ name”变量中。

现在,要真正解决您的问题,我需要指出两点:

1)您的XML <nombre>是VIVA COLOMBIA的大写字母,但与Volotea混合使用。其他<nombre>字段也有类似的问题。

2)您正在处理用户输入,这取决于输入的对象而可能相差很大。某些用户可能会键入所有大写字母,某些用户可能会键入小写字母(您称其为小写)。

真正的解决方法是,您应该将所有内容作为一种情况阅读。因此,这与原始版本相同:name = Console.ReadLine().ToUpper();

更改if (!String.IsNullOrEmpty(el.Element("nombre").Value.) && ((string)el.Element("nombre").Value.IndexOf(name) >= 0)

对此if (!String.IsNullOrEmpty(el.Element("nombre").Value.ToUpper()) && ((string)el.Element("nombre").Value.ToUpper()).IndexOf(name) >= 0)

相关问题