Read XML file, server returning error

Asked

Viewed 84 times

2

I wrote a code to read RSS feed that works well. If you access this URL will see that returns an XML in the browser, but when running in my code generates an internal error on the server and do not understand the reason. Someone can help me?

The code below is in dotNetFeedle. If uncomment the second link and comment the first you may see the error.

using System;
using System.Xml;

public class Program
{
    public static void Main()
    {

    string urlXml = "http://g1.globo.com/dynamo/tecnologia/rss2.xml";
    //string urlXml = @"http://migalhas.com.br/rss/rss.xml";

    //Cria novo documento XML local
    XmlDocument doc = new XmlDocument();

    //Tenta Carregar XML remoto em nosso XML local
    try
    {
        doc.Load(urlXml);
        XmlNodeList rssItems = doc.SelectNodes("//item");   

        int i = 0;
        foreach (XmlNode node in rssItems)
        {
            i++;
            Console.WriteLine(i + " - " + node["title"].InnerText);
            if(i==5)
            break;
        }    
    }
    catch (Exception ex)
    {
        Console.WriteLine("Erro:" + ex.Message);
    }
    //Selcecionar nós desejados usando xPath

    }
}

1 answer

2


Try this way with Webclient

//string urlXml = "http://g1.globo.com/dynamo/tecnologia/rss2.xml";
string urlXml = @"http://migalhas.com.br/rss/rss.xml";

var data = "";

using (var wc = new WebClient())
{
    wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");
    data = wc.DownloadString(urlXml);                
}

var reader = new XmlTextReader(new System.IO.StringReader(data));
while (reader.Read())
{
    Console.WriteLine(reader.Value);
}
  • 1

    It worked. Thank you very much

  • @Eduardonephew Wonder, don’t forget to mark as answered :)

  • Thiago, this is the first question answered here. I clicked on a 'checked' sign on the left side of your answer. Is this just to mark as answered? Again, thank you.

  • @Eduardonephew is right! That’s right, welcome to Stackoverflow!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.