Search code examples
c#xmlxml-parsingxmldocumentxmlreader

XML from URL - Data at the root level is invalid. Line 1, position 1 Why it works with one URL and not the other?


As far as I can tell, these two end points are both valid XML output. However when I use the same code on the second end point I get the error:

Data at the root level is invalid. Line 1, position 1

Here is my code:

        //Works
        XmlDocument testDocument = new XmlDocument();
        testDocument.Load("https://www.w3schools.com/xml/note.xml");

        //Fails
        XmlDocument testDocumentTwo = new XmlDocument();
        testDocumentTwo.Load("https://www.domainNameHere.com/direct/umbraco/api/productsearch/NameSearch?countryCode=en-gb");

Solution

  • I opened Fiddler and watched the request and its response, and lo and behold your endpoint is returning JSON, not XML:

    Fiddler screenshot, showing result is JSON

    If I use HttpClient to set an explicit Accept header, then I get XML back and everything works:

    using var client = new HttpClient();
    var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.clinigengroup.com/direct/umbraco/api/productsearch/NameSearch?countryCode=en-gb");
    requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
    var response = await client.SendAsync(requestMessage);
    var xml = await response.Content.ReadAsStringAsync();
    
    XmlDocument testDocumentTwo = new XmlDocument();
    testDocumentTwo.LoadXml(xml);