C# XmlDocument.LoadXml(string) failure (NotSupportedException)
The string which you want to parse has invalid character like ampersand.(&
)
DEPARTMENT is required for direct issues & reserves with backorders
Normally, the xml should be encoded properly. Using Replace
would be an option before trying to parse it.
var str = "<JOURNAL-SERVICE><ERROR>1</ERROR><ERRORMESSAGES>" +
"<ERRORMESSAGE>DEPARTMENT is required for direct issues & reserves with backorders</ERRORMESSAGE>" +
"</ERRORMESSAGES></JOURNAL-SERVICE>";
str = str.Replace("&", "&");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(str);
But, be sure about that the another non-encoded characters might be contained in the xml.
Strange behavior when loading xml via XmlDocument
Assuming filename is the path, try the below code.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
XmlDocument.Load loads XML either from a stream, TextReader, path/URL, or XmlReader and XmlDocument.LoadXml loads the XML contained within a string.
XmlDocument not reading file
The file is not unicode If you are not sure form your encoding you can do something like:
// path + filename !!
using (StreamReader streamReader = new StreamReader(dlg.FileName, true))
{
XDocument xdoc = XDocument.Load(streamReader);
}
or do that:
XDocument xdoc = XDocument.Parse(System.IO.File.ReadAllLines(dlg.FileName));
Read the link becarefully to understand the problem.
@ZachBurlingame solution; You have to do something like that:
Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?
// Encode the XML string in a UTF-8 byte array
byte[] encodedString = Encoding.UTF8.GetBytes(xml);
// Put the byte array into a stream and rewind it to the beginning
MemoryStream ms = new MemoryStream(encodedString);
ms.Flush();
ms.Position = 0;
// Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ms);
It must working!
Saving ONLY xml header in xml document throws error
A valid XML document must have a root element. This behavior is correct.
The definition of a well-formed XML document can be read at: https://www.w3.org/TR/xml/#sec-well-formed
How to read xml string ignoring header?
Well, it seems that there is no settings to ignore declaration, so I had to ignore it myself.
Here's the code I've written for those who might be interested:
private string _GetXmlWithoutHeadersAndComments(XmlDocument doc)
{
string xml = null;
// Loop through the child nodes and consider all but comments and declaration
if (doc.HasChildNodes)
{
StringBuilder builder = new StringBuilder();
foreach (XmlNode node in doc.ChildNodes)
if (node.NodeType != XmlNodeType.XmlDeclaration && node.NodeType != XmlNodeType.Comment)
builder.Append(node.OuterXml);
xml = builder.ToString();
}
return xml;
}
xml.LoadData - Data at the root level is invalid. Line 1, position 1
The hidden character is probably BOM.
The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.
Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}
I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object.
On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.
Related Topics
Export to Excel from a List with Epplus
How to Get the Last Day of a Month
How to Store Int[] Array in Application Settings
Reliably Stop System.Threading.Timer
Thread.Sleep for Less Than 1 Millisecond
Websocket Server: Onopen Function on the Web Socket Is Never Called
How to Get an Oauth 2.0 Authentication Token in C#
C# Selenium 'Expectedconditions Is Obsolete'
Playing a Mp3 File in a Winform Application
Fastest Method to Remove Empty Rows and Columns from Excel Files Using Interop
Must Declare Scalar Variable @Id
Merge Two (Or More) Lists into One, in C# .Net
Why C# Doesn't Implement Indexed Properties
ASP.NET Core MVC:How to Get Raw JSON Bound to a String Without a Type
Windows Phone 8.1 Universal App Terminates on Navigating Back from Second Page
Mapping Object to Dictionary and Vice Versa