简体   繁体   中英

XML deserialization: Data at the root level is invalid. Line 1 position 1. Tried almost everything

I'm trying to deserialize XML. I'm getting the XML to string(which works fine) but then when I try to parse it I'm getting and error "Data at the root level is invalid. Line 1 position 1" I tried everything which I found here. Read a lot of threads and tried all the suggestion: reading this to byte array, to stream, trying different Xml classes, removing BOM.

Here is my code(you can see the XML file under the link in code):

public class XmlParser
{
    private List<CurrencyUnit> _currenciesList = new List<CurrencyUnit>();
    public List<CurrencyUnit> CurrenciesList { get => _currenciesList; set => _currenciesList = value; }

    public async void GetXML()
    {
        Uri uri = new Uri("http://api.nbp.pl/api/exchangerates/tables/A/");

        HttpClient client = new HttpClient();


        HttpResponseMessage httpResponse = await client.GetAsync(uri);
        string response = await httpResponse.Content.ReadAsStringAsync();

        XDocument xDocument = XDocument.Parse(response);

        foreach (var element in xDocument.Descendants("Rate"))
        {
            CurrencyUnit unit = new CurrencyUnit();

            unit.Currency = element.Element("Currency").Value.ToString();
            unit.Code = element.Element("Code").Value.ToString();
            unit.Mid = element.Element("Mid").Value.ToString();
            CurrenciesList.Add(unit);
        }
    }
}

Here is part of the XML(you can see whole under the link from code):

 <?xml version="1.0" encoding="UTF-8"?> <ArrayOfExchangeRatesTable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <ExchangeRatesTable> <Table>A</Table> <No>056/A/NBP/2018</No> <EffectiveDate>2018-03-20</EffectiveDate> <Rates> <Rate> <Currency>bat (Tajlandia)</Currency> <Code>THB</Code> <Mid>0.1100</Mid> </Rate> 

That endpoint returns JSON if the request headers don't explicitly ask for XML, and you can't parse JSON as XML.

Your browser sends something like Accept: text/html,[...]application/xml by default, whereas HttpClient sends none. In that case, you get JSON in return. You could've seen this if you'd inspected the response variable while debugging.

Either deserialize the response into JSON, or pass the Accept: application/xml request header as explained in Forcing HttpClient to use Content-Type: text/xml .

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM