none
XML: how to create XDocument in memory and keep break on each XAttribute? RRS feed

  • Question

  • Our application needs to store XDocument as a Blob type in into database column. Later export this column as Xml file.

    We use the following code to create a XDocument in memory

    private static XDocument CreateXDocumentFromProperties()
    {
            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("Root",
              new XAttribute("DateCreate", DateTime.Now.ToShortDateString()),
              new XAttribute("ExpirationDate", ExpirationDate.ToShortDateString()),
              new XAttribute("LotNumber", LotNumber.ToString()),
              new XAttribute("PartNumber", PartNumber.ToString()),
              new XAttribute("ControlLotNumber", ControlLotNumber.ToString()),
              new XAttribute("Calib2", Calib2.ToString("D")),
              new XAttribute("Calib3", Calib3.ToString("D")),
              new XAttribute("Calib4", Calib4.ToString("D")),
              new XAttribute("Calib5", Calib5.ToString("D")),
              new XAttribute("Control1", Control1.ToString("D")),
              new XAttribute("Control2", Control2.ToString("D")),
              )));
           return doc;
     }
    XDocument doc = CreateXDocumentFromProperties();
    
    StringBuilder builder = new StringBuilder();
    using (TextWriter writer = new StringWriter(builder))
    {
        doc.Save(writer);
    }
    return builder.ToString();

    What we notice it store all attributes into one line.

    How do we break each XAttribute into one line? Thx!


    JaneC


    • Edited by JJChen Saturday, July 9, 2016 1:33 AM
    Saturday, July 9, 2016 1:33 AM

Answers

  • Try this:

    var settings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = true };
    using( var writer = XmlWriter.Create( builder, settings ) )
    {
      doc.Save( writer );
    }


    • Edited by Viorel_MVP Saturday, July 9, 2016 7:00 AM
    • Marked as answer by JJChen Wednesday, July 13, 2016 4:33 PM
    Saturday, July 9, 2016 7:00 AM