Viktors Jefimovs
Viktors Jefimovs

Reputation: 23

XML ReadLine to txt file

I have a problem with saving data from XML URL nodes, using XMLReader, to a text file. Can you please help me out? I don't know how to do it.

Here is the code:

namespace XMLdemo2
{
    class Program
    {
        static void Main(string[] args)
        {
            // Start with XmlReader object  
            String URLString = "https://www.shortcut.lv/xmls/tiesraide/ltv1.xml";
            XmlTextReader reader = new XmlTextReader(URLString);
            {
                while (reader.Read())
                {
                    if (reader.IsStartElement())
                    {

                        switch (reader.Name.ToString())
                        {


                            case "auth_token":
                                Console.WriteLine("Tokens IR : " + reader.ReadString());
                                break;
                        }

                        //Console.WriteLine("");
                    }


                }

                Console.ReadKey();
            }
        }
    }
}

Upvotes: 2

Views: 329

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26382

You can try something easier like this (if it's only one line you want to read)

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("https://www.shortcut.lv/xmls/tiesraide/ltv1.xml");
        XmlNode authTokenNode = xmlDoc.SelectSingleNode("//auth_token");
        if(authTokenNode != null)
            Console.WriteLine(authTokenNode.InnerText);

If it is multiple lines

        XmlDocument xmlDoc = new XmlDocument();
        XmlNodeList itemNodes = xmlDoc.SelectNodes("//auth_token");
        foreach(XmlNode itemNode in itemNodes)
        {
            if((itemNode != null)
                Console.WriteLine(itemNode.InnerText);
        }

Upvotes: 1

Related Questions