c# read a remote source XML file

Asked

Viewed 1,260 times

3

I have an API that generates me an XML but whenever I try to get the XML to handle the other side it returns me 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">
<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.'
  • What’s the mistake ?

  • sorry, updated there

1 answer

1


The problem is how to read the attributes, recommend desiccate to a class.

A valid example of a class to deselect its 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 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
        }
    }

Browser other questions tagged

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