Search code examples
c#text-filesstreamreader

Using streamreader in C# to save text between <h1></h1> tags in a string


I am using streamreader in C# and my goal is to read a text file with it and it must filter out text between the tags (like <Test> </Test> or <Name> </Name> ) And get the name of the tag like ( Test or Name) then save it to a string with the tag name for use later. I have searched the internet for a few days now but cant find anything, and i dont have much experience with C# but hope there is some one who can help me. The file itself is a .txt file

here is the code i have until now :

class Program
    {
        static void Main(string[] args)
        {

            using (StreamReader sr = new StreamReader(@"C:\testfile.txt"))
            {

                String line;
                // Read line by line
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);

                }
            }
            Console.ReadKey();
        }

    }

expected output is for example a string with name = everything between the name tag in plain text then test = everyting between the test tags in plain text. sorry for my bad english but i hope there is some one who can helpe me.


Solution

  • You can use XmlDocument

            XmlDocument Info_Document = new XmlDocument();
            Info_Document.Load(@"D:\saraxml.txt");
            XmlNodeList xmlnodelist = Info_Document.GetElementsByTagName("Name");//finding all nodes called "Name"
                foreach (XmlNode c in xmlnodelist)
                {
                   string _name=c.InnerText;
                }
    

    for this file :

    <test>
    <Name> h0</Name>
    
    <Name> h1</Name>
    
    <Name> h2</Name>
    
    <Name> h3</Name>
    
    <Name> h4</Name>
    
    <Name> h5</Name>
    </test>
    

    I got:

    h0

    h1

    h2

    h3

    h4

    h5