-5

I have following url which returns me XML response in c#: http://www.bnr.ro/files/xml/years/nbrfxrates2017.xml

Now, i want to retrieve the currency in Euro for my date which is present as a paramater in my function. I want to use Linq but i have some problems

My function:

public static void  getXml(String year, String data)
        {
            WebClient webClient = new WebClient();
            string url = "http://www.bnr.ro/files/xml/years/nbrfxrates" + year + ".xml";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(response.GetResponseStream());
            XElement xe = XElement.Load(response.GetResponseStream());
            var x = (from e in xe.Elements("Cube")
                     where e.Attribute("date").Value.Equals(data)
                     select e.Element("Rate") into p
                     where p.Element("currency").Value.Equals(data)
                     select p.Value);


            Console.WriteLine(x.ToString());


        }

My error is:

The root element is missing on XElement xe = XElement.Load(response.GetResponseStream());

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
S.over17
  • 199
  • 2
  • 2
  • 14

1 Answers1

1

Method GetResponseStream returns a stream:

Gets the stream that is used to read the body of the response from the server.

You cannot read this stream twice. When you load XmlDocument it reads data from network stream and closes it releasing the connection. When you try to load XElement from the closed stream, you get an error.

You should read response stream only once - e.g. into string or into MemoryStream:

string xml;
using(var reader = new StreamReader(r.GetResponseStream()))
    xml = reader.ReadToEnd();

Note: It's not clear why you need XmlDocument if you are using linq to xml.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459