My question is simple. I want to make sure LoadXml() works on below string.
"<?xml version='1.0' encoding='UTF-8'?><PDB><TRANSACTION_TYPE><TYPE>ERROR</TYPE></TRANSACTION_TYPE><ERROR><DESCRIPTION>Bad Input. Please check.</DESCRIPTION></ERROR></PDB>"
I tried all solutions at below links but nothing working for me in C# using .NET Framework 4.5.2
xml.LoadData – Data at the root level is invalid. Line 1, position 1
Why “Data at the root level is invalid. Line 1, position 1.” for XML Document?
StartsWith change in Windows Server 2012
I am calling a API which I do not have any control on it.
After doing string responseData = reader.ReadToEnd();
In responseData I have string like this
"<?xml version='1.0' encoding='UTF-8'?><PDB><TRANSACTION_TYPE><TYPE>ERROR</TYPE></TRANSACTION_TYPE><ERROR><DESCRIPTION>Bad Input. Please check.</DESCRIPTION></ERROR></PDB>"
I tried many codes like below and no matter what I try everytime I get
System.Xml.XmlException: Data at the root level is invalid. Line 1, position 201.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.LoadXml(String xml)
Below is sample code.
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
{
if (response.StatusCode == HttpStatusCode.Created)
{
using (var respStream = response.GetResponseStream())
{
using (var reader = new System.IO.StreamReader(respStream, true))
{
string responseData = reader.ReadToEnd();
if (responseData.Contains(@"<TYPE>ERROR</TYPE>"))
{
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (responseData.StartsWith(_byteOrderMarkUtf8, StringComparison.Ordinal))
{
responseData = responseData.Remove(0, _byteOrderMarkUtf8.Length);
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseData);
}
}
}
}
}