How to deserialize attributes of the elements of an XML with C#?

Asked

Viewed 536 times

0

Well, I asked that question once, but I didn’t get an answer, so I’m gonna ask you again. I tried some methods I saw there that said it worked in other questions, but none of them.

I need to read this XML:

http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoAjax.asp?CodigoPapel=BISA3|PETR4|PETR3

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 a hard time playing the values of the attributes in variables to parameterize. If anyone can help me, I’d appreciate it.

  • I don’t think it’s duplicate. He wants a deserialization, not necessarily read attribute to attribute, otherwise the answer indicated would perfectly meet.

  • @Ciganomorrisonmendez is actually the same question, only written differently.

  • 1

    I was going to speak on the previous question too, but I thought the duplicate might help. As it did not solve, I put another answer.

1 answer

3


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

Below I detail a script that can serve your problem.

Reading the XML

This first step requires you to 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 response to XML

If response is ok, we have to read XML. As your XML does not have namespace, the reading 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’ll put a proof of concept on Github.

  • 1

    Thanks it worked I gave some tweaked here to suit my logic and it worked even thanks , sorry to bother and ask two identical questions and that in this I wanted to be more specific than n other helped quite even vlw :)

  • @Filipe I apologize for not having tried this answer before. I had a code very similar here already ready that I adapted to your reality. Feel free to ask more if you have any further questions.

Browser other questions tagged

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