I'm working on some code to read an XML fragment which contains an XML declaration, e.g. <?xml version="1.0" encoding="utf-8"?>
and parse the encoding. From MSDN, I should be able to do it like this:
var nt = new NameTable();
var mgr = new XmlNamespaceManager(nt);
var context = new XmlParserContext(null, mgr, null, XmlSpace.None);
var reader = new System.Xml.XmlTextReader(@"<?xml version=""1.0"" encoding=""UTF-8""?>",
System.Xml.XmlNodeType.XmlDeclaration, context);
However, I'm getting a System.Xml.XmlException
on the call to the System.Xml.XmlTextReader
constructor with an error message:
XmlNodeType XmlDeclaration is not supported for partial content parsing.
I've googled this error in quotes -- exactly zero results found (edit: now there's one result: this post) -- and without quotes, which yields nothing useful. I've also looked at MSDN for the XmlNodeType, and it doesn't say anything about it not being supported.
What am I missing here? How can I get an XmlTextReader
instance from an XML declaration fragment?
Note, my goal here is just to determine the encoding of a partially-built XML document where I'm making the assumption that it at least contains a declaration node; thus, I'm trying to get reader.Encoding
. If there's another way to do that, I'm open to that.
At present, I'm parsing the declaration manually using regex, which is not the best approach.
Maybe late but you can use below code after loading it in a XmlDocument
If you have a byte array as input, try something like this:
Update: Getting the encoding from XML documentation or from XML fragment:
Here's a way to get the encoding without having to resort to fake root, using XmlReader.Create.
Here's the output, with a full and fragment XML:
If you want to have System.Text.Encoding, you can modify the code to look like this:
Old answer:
As you mentioned, XmlTextReader's Encoding-property contains the encoding.
Here's a full Console app's source code which hopefully is useful:
Here's the output from the program:
If you know that the XML only contains the declaration, maybe you can add an empty root? So for example:
Good evening, here's the solution with a System.Text.Encoding as output. I made it to be clear, and step by step.