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

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

Related

Data at the root level is invalid. Line 1, position 1. Is it error with the xml format?

Im having a problem with reading my xml with an error of Data at the root level is invalid. Line 1,position 1.
This is my code below:
string soapmessage = response.Content;
XmlDocument xml = new XmlDocument();
xml.LoadXml(soapmessage); //loading soap message as string
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
below attached my XML response

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

XDocument Load - cannot open

I'm trying to load rss feed by XDocument.
The url is:
http://www.ft.com/rss/home/uk
XDocument doc = XDocument.Load(url);
But I'm getting an error:
Cannot open 'http://www.ft.com/rss/home/uk'. The Uri parameter must be a file system relative or absolute path.
XDocument.Load does not take URL's, only files as stated in the documentation.
Try something like the following code which I totally did not test:
using(var httpclient = new HttpClient())
{
var response = await httpclient.GetAsync("http://www.ft.com/rss/home/uk");
var xDoc = XDocument.Load(await response.Content.ReadAsStreamAsync());
}

Web API Request Data error on second time

Strange Error.
var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(this.Request.Content.ReadAsStreamAsync().Result);
var xmlDoc1 = new System.Xml.XmlDocument();
xmlDoc1.Load(this.Request.Content.ReadAsStreamAsync().Result);
In WEB API, I try to load the POST data in to xmlXoc it is working good
When I try to load it again in to xmlDoc1 (new variable), I am getting a Root Element missing error.
I see that ReadAsStreamAsync is a Read-Only-Stream but why the error on the last line ?
Save the Stream in a local variable and reset it to the beginning when reading it a second time.
var stream = this.Request.Content.ReadAsStreamAsync().Result
var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(stream);
// RESET
stream.Position = 0;
var xmlDoc1 = new System.Xml.XmlDocument();
xmlDoc1.Load(stream);

How can i send an XML file as an object to some other function

I needed to read(load) one xml file, and send the same file as an object to other function. Here the problem I am facing is, while loading the file, it is converted to XML Object. Now we can get the details of the file by accessing the InnerXML property, where it got converted to String.
How can I get this String object get assigned to an normal Object whose properties are internally similar to this xml?
See the sample:
SearchResponse Response = new SearchResponse();
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\Search_Response.xml");
Object response = new Object();
response = doc.InnerXml;
Response = (SearchResponse)response;
return Response;
Please help me out!
You can achieve this by Serialization.
use Microsoft.Http.HttpClient. This will give you to convert Xml to Object Very easily.
Eg:
SearchResponse Response = new SearchResponse();
var client = new HttpClient();
var httpResponseMessage = client.Get(uri);
Response = httpResponseMessage.Content.ReadAsXmlSerializable<SearchResponse >();

Categories

Resources