Align Attributes when Formatting XML using LINQ to XML
A few years ago, I wrote a blog post that showed how to align attributes when formatting XML using LINQ to XML. Here is an extension method that uses that technique.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
public static class Extensions
{
public static string ToStringAlignAttributes(this XContainer xContainer)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
settings.NewLineOnAttributes = true;
StringBuilder sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb, settings))
xContainer.WriteTo(xmlWriter);
return sb.ToString();
}
}
class Program
{
static void Main(string[] args)
{
XDocument doc = new XDocument(
new XElement("Root",
new XAttribute("att1", 1),
new XAttribute("att2", 2),
new XAttribute("att3", 3),
new XElement("Child",
new XAttribute("att1", 1),
new XAttribute("att2", 2),
new XAttribute("att3", 3))));
Console.WriteLine(doc.ToStringAlignAttributes());
XElement el = new XElement("Root",
new XAttribute("att1", 1),
new XAttribute("att2", 2),
new XAttribute("att3", 3),
new XElement("Child",
new XAttribute("att1", 1),
new XAttribute("att2", 2),
new XAttribute("att3", 3)));
Console.WriteLine(el.ToStringAlignAttributes());
}
}
}
Update: May 5, 2011 – I initially wrote a more fancy version of this, but as it turns out, I got it wrong – it didn’t properly indent some cases of some XML documents, so am reverting the code. When I get a chance, I’ll work out the issues with the code that implements more fancy alignment.