CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
// https://stackoverflow.com/questions/47881189/xml-entities-in-json-net
class TestClass
{
public static void Test()
{
string xml = @"<?xml version='1.0' standalone='no'?>
<!DOCTYPE notes [
<!ENTITY ent 'Sample text'>
]>
<notes>
<note>&ent;</note>
</notes>";
var json2 = Test2(xml);
var json1 = Test1(xml);
Assert.IsTrue(json2 == json1);
Console.WriteLine("\nXDocument and XmlDocument produce identical results.");
}
private static string Test2(string xml)
{
Console.WriteLine("\nTesting XDocument...");
var doc = XDocument.Parse(xml);
string json = JsonConvert.SerializeXNode(doc, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
return json;
}
private static string Test1(string xml)
{
Console.WriteLine("\nTesting XmlDocument...");
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);
return json;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}
public class AssertionFailedException : System.Exception
{
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
}
public static class Assert
{
public static void IsTrue(bool value)
{
IsTrue(value, "failed");
}
public static void IsTrue(bool value, string message)
{
if (value == false)
throw new AssertionFailedException(message ?? "failed");
}
}