using System.Collections.Generic;
public static class XDocumentExtensions
static readonly XmlReaderSettings noCheckedCharacterParseSettings = new() { CheckCharacters = false, };
static readonly XmlReaderSettings checkedCharacterParseSettings = new() { CheckCharacters = true, };
public static XDocument Parse(string xml, bool checkCharacters) =>
Parse(xml, checkCharacters ? checkedCharacterParseSettings : noCheckedCharacterParseSettings);
public static XDocument Parse(string xml, XmlReaderSettings settings)
using var reader = new StringReader(xml);
using var xmlReader = XmlReader.Create(reader, settings);
return XDocument.Load(xmlReader);
static readonly XmlWriterSettings noCheckedCharacterToStringSettings = new() { CheckCharacters = false, Indent = true, OmitXmlDeclaration = true, };
static readonly XmlWriterSettings checkedCharacterToStringSettings = new() { CheckCharacters = true, Indent = true, OmitXmlDeclaration = true, };
public static string ToString(this XNode node, bool checkCharacters) =>
node.ToString(checkCharacters ? checkedCharacterToStringSettings : noCheckedCharacterToStringSettings);
public static string ToString(this XNode node, XmlWriterSettings settings)
using var writer = new StringWriter();
using (var xmlWriter = XmlWriter.Create(writer, settings))
return writer.ToString();
public static void Test()
Console.WriteLine("Testing XmlDocument:");
string message = "Hello, \x01\x1EWorld!";
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("greeting");
xmlDoc.AppendChild(root);
root.InnerText = message;
Console.WriteLine(xmlDoc.OuterXml);
var xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(xmlDoc.OuterXml);
Console.WriteLine(xmlDoc2.OuterXml);
string xmlWithEscapedHexEntity = xmlDoc.OuterXml;
xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlWithEscapedHexEntity);
Console.WriteLine(xmlDoc.OuterXml);
Console.WriteLine("\nTesting XDocument:");
XDocument xdoc = new XDocument(
new XElement("greeting", message)
Console.WriteLine(xdoc.ToString(checkCharacters : false));
Console.WriteLine($"XDocument creation error: {ex}");
XDocument xDoc = XDocumentExtensions.Parse(xmlWithEscapedHexEntity, checkCharacters : false);
Console.WriteLine(xDoc.ToString(checkCharacters : false));
Console.WriteLine($"XDocument parse failure: {ex}");
public static void Main()
Console.WriteLine("Environment version: {0} ({1}, {2}, NewLine: {3}).",
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion,
System.Text.Json.JsonSerializer.Serialize(Environment.NewLine));
Console.WriteLine("Failed with unhandled exception: ");