I did not find a way to use .NET XmlWriter and its associated XmlWriterSettings to format indented XML strings exactly as Visual Studio does with its automatic formatting command (Ctrl-E Ctrl-D or, depending on the keyboard, Ctrl-K Ctrl-D).
I would like to do this because I usually automatically formatted all my files in VS, both in code and in .config files. I have an installer application that updates .config files and I would like the actual differences to be changed instead of the whole document.
I did not study all the different formatting options for the automatic format, but I like that each XML attribute is on a separate line, the first on the same line as the opening tag, and the subsequent ones queued with the first, like this:
<asset assetId="12345" bucket="default" owner="nobody"> <file path="\\localhost\share\assetA.mov"/> <metadata metadataId="23456" key="asset_type" value="video"/> </asset>
I tried formatting using the XmlWriterSettings properties "NewLineHandling = NewLineHandling.None" and "NewLineOnAttributes = true", but this puts the first attribute below the opening tag, and all attributes have the same indentation, regardless of # characters in the element name, for example:
<asset assetId="12345" bucket="default" owner="nobody"> <file path="\\localhost\share\assetA.mov" /> <metadata metadataId="23456" key="asset_type" value="video" /> </asset>
Note that the standard XmlWriter also closes attribute elements with "/"> "(extra space before the slash), which I don’t like, but not sure if this XML standard. I would think that Visual Studio uses the same options APIs that are easily accessible by developers, but I have not found these magic settings yet.Anyway, here is my format method:
public static string FormatXml( string xmlString, bool indented ) { using ( TextReader textReader = new StringReader( xmlString ) ) using ( XmlReader xmlReader = new XmlTextReader( textReader ) ) { using ( TextWriter textWriter = new StringWriter() ) { var settings = new XmlWriterSettings(); if ( indented ) { settings.Indent = true; settings.IndentChars = " "; settings.NewLineOnAttributes = true; settings.NewLineHandling = NewLineHandling.None; } using ( var xmlWriter = XmlWriter.Create( textWriter, settings ) ) { while ( xmlReader.Read() ) xmlWriter.WriteNode( xmlReader, false ); } return textWriter.ToString(); } } }
Erhhung
source share