0

I've to save xml file in to database after serialising it, this is so that the other Module that uses this sequence to again create the same XML file and use it.

Problem is with my current approach it does it but all in one line. How should I go about so that it create the sequence with correct indentation ?

public static byte[] ConvertXMLToByteArray(XDocument xml)
    {
        // Init Writers
        StringWriter sw = new StringWriter();
        XmlTextWriter xw = new XmlTextWriter(sw);

        // Save Xml to Text Writer.
        xml.WriteTo(xw);
        UTF8Encoding encoding = new System.Text.UTF8Encoding(false);

        // Convert Xml Document To Byte Array with given encoding
        return encoding.GetBytes(sw.ToString());
    }
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
AlphaTry
  • 475
  • 5
  • 27
  • 2
    What do you mean "with correct indentation"? Are you asking two questions here?: 1. How to pretty print XML. 2. How to save XML to a byte array? – ProgrammingLlama Sep 04 '18 at 12:02
  • 1
    XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter xw = XmlWriter.Create(sw, settings); – jdweng Sep 04 '18 at 12:12
  • 2
    The indentation doesn't affect the *information content* of the XML and if you're just round-tripping XML via a byte array, that's all you should care about. In the database (if it doesn't natively support XML), you should just go for the most compact form. – Damien_The_Unbeliever Sep 04 '18 at 12:13
  • 1
    Possible duplicate of [How do you create an indented XML string from an XDocument in c#?](https://stackoverflow.com/questions/2374654/how-do-you-create-an-indented-xml-string-from-an-xdocument-in-c) – Ofir Winegarten Sep 04 '18 at 12:13
  • Your title seems to mislead and confuse. The indentation has nothing to do with the fact that you convert it to bytes. The string that you generate is not indented. You can use `XmlWriterSettings` as @jdweng commented, or simply `xml.ToString()` – Ofir Winegarten Sep 04 '18 at 12:17
  • To add to @Damien_The_Unbeliever comment. Formatting is for humans, computers don't (or at least, shouldn't) care. – Neil Sep 04 '18 at 12:23

0 Answers0