You can do this using XmlWriter . Try the following:
public static string ToStringFormatted(this XElement xml) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = true; StringBuilder result = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(result, settings)) { xml.WriteTo(writer); } return result.ToString(); }
then
var xml =new XElement("options", new XAttribute("updated", "U"), new XAttribute("color", "C"), new XAttribute("puppies", "P"), new XAttribute("isTrue", "I"), new XAttribute("kitties", "K") ); Console.WriteLine(xml.ToStringFormatted());
produces the following:
<options updated="U" color="C" puppies="P" isTrue="I" kitties="K" />
You may have different formatting using various XmlWriterSettings properties.
source share