简体   繁体   中英

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");

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

Fiddler 截图,显示结果为 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);

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