pfirth3
pfirth3

Reputation: 21

ServiceStack.Text xml serialization nicely formatted output

Is it possible for ServiceStack.Text to indent its xml output so it is not one long line of xml? We would like to write the output to a text file that is easily readable.

Upvotes: 2

Views: 534

Answers (1)

Senthilkumar Elangovan
Senthilkumar Elangovan

Reputation: 675

Are you using any kind of encoding. Because by default there wont be any indent stripping will happen when you serialize your object. Try the below code.

Your xml class object

 public class MyXMLClass
{
    [XmlElement]
    public string[] Property1 { get; set; }
    [XmlElement]
    public string[] Property2 { get; set; }
}    

Serialize method

static void TestXMLWithIndent()
    { 
        var x = new MyXMLClass()
        {
            Property1 = new string[] { "TestProp11", "TestProp12", "TestProp13" },
            Property2 = new string[] { "TestProp21", "TestProp22", "TestProp23" }
        };
        var filename = @"c:\temp\testxmlWithIndent.oxi";
        using (TextWriter textWriter = new StreamWriter(filename))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MyXMLClass));
            serializer.Serialize(textWriter, x);
            textWriter.Close();
        }
    }

This code produce correct indent. Whereas the below code produce xml file with no indent as you mentioned. Please note, I have to use encoding when I use xmltextwriter.

 static void XmlWithNoIndent()
    {
        var x = new MyXMLClass()
        {
            Property1 = new string[] { "TestProp11", "TestProp12", "TestProp13" },
            Property2 = new string[] { "TestProp21", "TestProp22", "TestProp23" }
        };
        var filename = @"c:\temp\testxmlWithNoIndent.oxi"; 
        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (var xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.Unicode))
            {
                XmlSerializer xs = new XmlSerializer(typeof(MyXMLClass));
                xs.Serialize(xmlTextWriter, x);

                MemoryStream memoryBaseStream;
                memoryBaseStream = (MemoryStream)xmlTextWriter.BaseStream;
                UTF8Encoding encoding = new UTF8Encoding();
                File.WriteAllBytes(filename, memoryStream.ToArray());
                memoryBaseStream.Dispose();
                xmlTextWriter.Close();
                memoryStream.Close();
            }
        }
    }

Upvotes: 2

Related Questions