30

When using the default settings with the XmlSerializer it will output the XML as a formated value.

IE: something along these lines.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Stock>
    <ProductCode>12345</ProductCode>
    <ProductPrice>10.32</ProductPrice>
  </Stock>
  <Stock>
    <ProductCode>45632</ProductCode>
    <ProductPrice>5.43</ProductPrice>
  </Stock>
</ArrayOfStock>

How does one prevent any type of formatting on the output? So what I am looking to achieve is this.

<?xml version="1.0" encoding="utf-8"?><ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Stock><ProductCode>123456</ProductCode><ProductPrice>10.57</ProductPrice></Stock><Stock><ProductCode>789123</ProductCode><ProductPrice>133.22</ProductPrice></Stock></ArrayOfStock>

EDIT: The full code of my method is

public static String Serialize(Stock stock)
{
     XmlSerializer serializer = new XmlSerializer(typeof(Stock));

     using (StringWriter stringWriter = new StringWriter())
     {
         serializer.Serialize(stringWriter, stock);
         return stringWriter.ToString();
     }            
}
Jacek Przemieniecki
  • 5,757
  • 1
  • 12
  • 15
Maxim Gershkovich
  • 45,951
  • 44
  • 147
  • 243

3 Answers3

47

Not very intuitive, but the Indent property on the XmlWriterSettings controls the whole formatting:

var serializer = new XmlSerializer(typeof(MyClass));

using (var writer = new StreamWriter("file.path"))
using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { Indent = false }))
{
    serializer.Serialize(xmlWriter, myObject);
}

There are a few more options on XmlWriterSettings that you might want to explore.

Xavier Poinas
  • 19,377
  • 14
  • 63
  • 95
  • 3
    I think Indent is by default false because I had same code as yours (without Settings) and wanted it formatted so I had to change Indent to true. – sluki Sep 02 '14 at 06:49
  • 5
    Yes, Indent is false by default on `XmlWritterSettings` so I guess it can be omitted from the code above. But if you use the `XmlSerializer` without explicitly giving it an `XmlWriter`, it will use its own and enable formatting/indenting by default. – Xavier Poinas Mar 01 '16 at 05:03
  • The comment from @XavierPoinas about default value is very important. – Kristoffer Jälén Nov 02 '20 at 10:09
0

..

XmlSerializer xmlser = new XmlSerializer(...);

XmlWriterSettings settings = new XmlWriterSettings {Indent = false};

using (XmlWriter xw = XmlWriter.Create(stream, settings))
{

...

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Ivan G.
  • 5,027
  • 2
  • 37
  • 65
0

It is simple to parse the resulting XML and remove and newlines and tabs...
using 'Indent = false', will still put elements on newlines no?

Aaron Gage
  • 2,373
  • 1
  • 16
  • 15