Enter line breaks / carriage returns between XAttributes as a result of XElement.ToString

Is there no way to get line breaks between attributes in an XML string of XElement.ToString result?

The following did not work - it kept line breaks, but placed them below all attributes, so there were only 4/5 empty lines:

new XElement("options", new XText("\r\n"), new XAttribute("updated", Updated.XmlTime()), new XText("\r\n"), new XAttribute("color", Color), new XText("\r\n"), new XAttribute("puppies", Puppies), new XText("\r\n"), new XAttribute("isTrue", IsTrue), new XText("\r\n"), new XAttribute("kitties", Kitties ?? "")), 
+4
source share
2 answers

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(); } // ToStringFormatted 

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.

+6
source

It is not possible to place new lines inside an XML object because there are no β€œtext nodes” between attributes in the XML DOM. All attributes for each node are in a large unordered * table, and there are no text-only attributes.

Only a textual representation of XML can have such attribute formatting. Note that all formatting between attributes will be lost when such XML is loaded into the DOM / reader.

What you can do is implement your own XmlWriter with the right formatting.

*) Most XML DOM implementations preserve the order of the attributes, both in the source and in the order in which they are added, but this is not required.

0
source

All Articles