How to deserialize attributes of XML elements with C #? [duplicate]

0

Well I asked this question once but I did not have an answer, so I'll ask again. I've tried some methods I saw there that said that worked on other questions, but none of them.

I need to read this XML:

link

And extract the attributes of the elements to play in a database. The part of the bank I already know how to do, I'm just having difficulty playing the values of the attributes in variables to parameterize. If anyone can help me, thank you.

    
asked by anonymous 21.06.2015 / 17:31

1 answer

3

What you really want is a deserialization : transform an XML into an object that can be read and fill variables to persist in your database.

Below I detail a roadmap that may serve your problem.

Reading XML

This first step requires that you open a request for the site and read the response (which is XML). The code below does this:

using System.Net.Http;

var client = new HttpClient();

var uri = new Uri("http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoAjax.asp?CodigoPapel=BISA3|PETR4|PETR3");
HttpResponseMessage response = await client.GetAsync(uri);

Converting the XML response

If response is ok, we have to read the XML. Since your XML does not have namespace , the read procedure is simpler and can be done as follows:

if (response.IsSuccessStatusCode)
{
    var responseString = response.Content.ReadAsStringAsync().Result;
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(responseString);
    var nodes = xmlDoc.SelectNodes("/ComportamentoPapeis/*");

    foreach (XmlNode childNode in nodes)
    {
        switch (childNode.Name)
        {
            case "Papel":
                // Coloque sua lógica de negócios aqui.
                // A dica que dou pro seu caso é ler childNode.Attributes.
                break;
        }
    }

If I need to, I put a proof of concept on GitHub.

    
21.06.2015 / 18:14