CSharp · Console
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Reflection;
using NUnit.Framework; //NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/79185507/xdocument-convert-open-and-close-tags-to-self-closing-tag
#nullable enable
public static partial class XmlExtensions
{
public static void CleanUpXElements(this XDocument doc)
{
foreach (XElement childElement in
from x in doc.Descendants()
where !x.IsEmpty && !x.Elements().Any() && string.IsNullOrEmpty(x.Value)
select x)
{
childElement.RemoveNodes();
};
}
public static void CleanUpXElementsOrig(this XDocument doc)
{
foreach (XElement childElement in
from x in doc.DescendantNodes().OfType<XElement>()
where x.Value == string.Empty
select x)
{
childElement.ReplaceWith(new XElement(childElement.Name.LocalName, childElement.Attributes()));
};
}
}
public class TestClass
{
public static void Test()
{
var xml = """<Foo><GovtID id="1"></GovtID><Bar>xxx<p></p></Bar></Foo>""";
Console.WriteLine("Testing fixed method:");
TestFix(xml);
Console.WriteLine("Fix successful.\n");
Console.WriteLine("Testing original method:");
try
{
TestOriginal(xml);
Console.WriteLine("original method successful.\n");
}
catch (Exception ex)
{
Console.WriteLine("original method failed with exception:\n{0}\n", ex);
}
}
static void TestFix(string xml)
{
var doc = XDocument.Parse(xml);
Console.WriteLine(doc);
//Dump XContainer.content:
//https://github.com/microsoft/referencesource/blob/master/System.Xml.Linq/System/Xml/Linq/XLinq.cs#L2318
//IsEmpty checks for a null content so we need to call a method that nulls it out.
var govtId = doc.Root!.Element("GovtID")!;
Console.Write("Value of XContainer.content before modification: ");
govtId.GetType().GetField("content", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(govtId)!.Dump();
doc.CleanUpXElements();
Console.WriteLine(doc);
Console.Write("Value of XContainer.content AFTER modification: ");
govtId.GetType().GetField("content", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(govtId)!.Dump();
}
static void TestOriginal(string xml)
{
var doc = XDocument.Parse(xml);
Console.WriteLine(doc);
doc.CleanUpXElementsOrig();
Console.WriteLine(doc);
}
}
public class Program
{
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();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}