c# read a remote source XML file


I have an API that generates an XML for me, but whenever I try to get the XML to handle on the other side, it returns an error.

the XML is this:

<ArrayOfResponsaveis xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/webservice.Models">
<nome>danilo dorgam</nome>

the code I use to read the XML is this

public Boolean setLogin(string matricula, string senha)
    string url = URL_WEBSERVICE+matricula+"/"+senha;
    var xdoc = XDocument.Load(@url);
    var lv1s = from lv1 in xdoc.Descendants("Responsaveis")
               where (string) lv1.Element("id").Value == "1"
               select lv1;
    return false;

but in XDocument.Load it crashes and shows the following error

System.Xml.XmlException: 'Dados no nível raiz inválidos. Linha 1, posição 1.'


The problem is the way to read the attributes, I recommend doing this for a class.

A valid example of a class to deseque your xml in model https://paste.ofcode.org/BDAVPU5T5sZ7xZ4kfjUmea

NOTE: Just copy the XML go to visual studio > Edit > Special Paste > XML to class

Reading XML via the web.

using System.Net.Http;

var client = new HttpClient();
var uri = new Uri(url);
HttpResponseMessage response = await client.GetAsync(uri);

Method 1 – Serializing:

var responseString = response.Content.ReadAsStringAsync().Result;
    var serializer = new XmlSerializer(typeof(ArrayOfResponsaveis));
    return (ArrayOfResponsaveis)serializer.Deserialize(responseString);

Method 2 – Reading the attributes

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

    foreach (XmlNode childNode in nodes)
        switch (childNode.Name)
Scroll to Top