Search code examples
c#.netxelement

Enter line-breaks / carriage returns between the XAttributes in a XElement.ToString result


Is there no way to get line-breaks to appear between attributes in the XElement.ToString resultant xml string?

The following didn't work -- it kept the line-breaks, but put them below all the attributes, so there were just 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 ?? "")),

Solution

  • You can do it using a XmlWriter. Try this:

    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 this:

    <options
      updated="U"
      color="C"
      puppies="P"
      isTrue="I"
      kitties="K" />
    

    You can have different formatting using the various XmlWriterSettings properties.