The exception is explanatory: Json.NET apparently hasn't implemented conversion of XmlEntityReference
nodes to JSON. This is the XmlNode
subtype that is used to represent the &ent;
entity reference.
To avoid the limitation you will need to expand entities while reading your XML, for instance like so:
var settings = new XmlReaderSettings
{
// Allow processing of DTD
DtdProcessing = DtdProcessing.Parse,
// On older versions of .Net instead set
//ProhibitDtd = false,
// But for security, prevent DOS attacks by limiting the total number of characters that can be expanded to something sane.
MaxCharactersFromEntities = (long)1e7,
// And for security, disable resolution of entities from external documents.
XmlResolver = null,
};
XmlDocument doc = new XmlDocument();
using (var textReader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(textReader, settings))
{
doc.Load(xmlReader);
}
string json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
Notes:
Or you could switch to the XDocument
API in which entities are always expanded and security settings are more appropriate by default:
var doc = XDocument.Parse(xml);
string json = JsonConvert.SerializeXNode(doc, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
Working .Net fiddle showing that the &ent;
node gets expanded to its value Sample text
:
{
"?xml": {
"@version": "1.0",
"@standalone": "no"
},
"!DOCTYPE": {
"@name": "notes",
"@internalSubset": "\n <!ENTITY ent 'Sample text'>\n "
},
"notes": {
"note": "Sample text"
}
}