c # read a remote source XML file

3

I have an API that generates an XML however whenever I try to get the XML to handle the other side it returns an error.

XML is this:

<ArrayOfResponsaveis xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/webservice.Models">
<Responsaveis>
<id>1</id>
<matricula>uc14100703</matricula>
<nivel>1</nivel>
<nome>danilo dorgam</nome>
<senha>xxxx</senha>
</Responsaveis>
</ArrayOfResponsaveis>

The code I use to read 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 hangs and shows the following error

System.Xml.XmlException: 'Dados no nível raiz inválidos. Linha 1, posição 1.'
    
asked by anonymous 12.06.2017 / 21:08

1 answer

1

The problem is how to read the attributes, I recommend deserializing for a class.

A valid example of a class to deserialize its xml in model link

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

Reading the 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();
    xmlDoc.LoadXml(responseString);
    var nodes = xmlDoc.SelectNodes("/Responsaveis/*");

    foreach (XmlNode childNode in nodes)
    {
        switch (childNode.Name)
        {
         //logica
        }
    }
    
22.08.2017 / 18:50