I have the following that I'm using the serialize my XML document:
XmlWriter xw = XmlWriter.Create(sbXmlDoc, new XmlWriterSettings {
Indent = true,
IndentChars = " ",
OmitXmlDeclaration = true
});
That creates an instance of System.Xml.XmlWellFormedWriter
which for some reason is internal
so I can't extend / override it. It outputs empty elements like <element />
instead of <element/>
, putting the extra space in. Is there any way I can customize the output so as to remove that extra space before the trailing slash? I'm aware of XmlTextWriter
but it seems to be recommended to use XmlWriter.Create()
instead now.
Here is a generic solution by using Saxon and XSLT 3.0
The XSLT is one single line, it using a so called Identity Transform pattern.
It will work with any XML file.
You have a full control over indentation, XML declaration, encoding, BOM, etc.
You will find there the SaxonHE10-9N-setup.exe installation file in the Dotnet folder.
Input XML
<root>
<city>Miami</city>
<state />
</root>
XSLT 3.0
<?xml version="1.0"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" expand-text="yes">
<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="no"/>
<xsl:strip-space elements="*"/>
<xsl:mode on-no-match="shallow-copy"/>
</xsl:stylesheet>
Output XML
<?xml version="1.0" encoding="utf-8"?>
<root>
<city>Miami</city>
<state/>
</root>
c#
void Main()
{
const string XSLTFILE = @"c:\Saxon-HE 10\IdentityTransform.xslt";
const string INFILE = @"c:\Saxon-HE 10\input.xml";
const string OUTFILE = @"c:\Saxon-HE 10\output.xml";
// Create a Processor instance.
Processor processor = new Processor();
// Load the source document
XdmNode input = processor.NewDocumentBuilder().Build(new Uri(INFILE));
// Create a transformer for the stylesheet.
Xslt30Transformer transformer = processor.NewXsltCompiler().Compile(new Uri(XSLTFILE)).Load30();
// Create a serializer, with output to the standard output stream
Serializer serializer = processor.NewSerializer();
serializer.SetOutputStream(new FileStream(OUTFILE, FileMode.Create, FileAccess.Write));
// Transform the source XML and serialize the result document
transformer.ApplyTemplates(input, serializer);
Console.WriteLine("Output written to '{0}'", OUTFILE);
}