简体   繁体   中英

C# Serialize object into xml without formatting

I need to serialize a c# object into xml, i could do it as in formatted section, but can we achieve it without formatting that has no indentation/extra spaces/new lines. This is required as we need to write the whole object into a csv, so we need a minified version. I tried couple of XmlWriterSettings, but it did not work as expected. Any code snippet will be of great help and the object to be serialized can have other reference types as members that may inherit from other base class, so serializer may need known types

Formatted XML:

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

Without Formatting:

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

Code Tried:

Type[] _knownExpressions = new Type[]
{
     typeof(SimpleExpression),
     typeof(CompositeExpression)
};
string expression = string.Empty;
MemoryStream ms = new MemoryStream();
DataContractSerializer dcs = new DataContractSerializer(typeof(Expression), _knownExpressions);                                        
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(ms, System.Text.Encoding.Default))
{
      xmlTextWriter.Formatting = Formatting.None;
      dcs.WriteObject(xmlTextWriter, expression);
      xmlTextWriter.Flush();
      xmlTextWriter.BaseStream.Position = 0;
      StreamReader sr = new StreamReader(xmlTextWriter.BaseStream);
      expression = sr.ReadToEnd();
      sr.Close();
 }

Don't mind, I wasn't passing the right object to the serializer, the following works

Type[] _knownExpressions = new Type[]
{
     typeof(SimpleExpression),
     typeof(CompositeExpression)
};
string expression = string.Empty;
Expression exp = new Expression(){
   // Fill the object
};
MemoryStream ms = new MemoryStream();
DataContractSerializer dcs = new DataContractSerializer(typeof(Expression), _knownExpressions);                                        
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(ms, System.Text.Encoding.Default))
{
      xmlTextWriter.Formatting = Formatting.None;
      dcs.WriteObject(xmlTextWriter, exp);
      xmlTextWriter.Flush();
      xmlTextWriter.BaseStream.Position = 0;
      StreamReader sr = new StreamReader(xmlTextWriter.BaseStream);
      expression = sr.ReadToEnd();
      sr.Close();
 }

Xml Writer defaults to Ident = false. So following will work:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication137
{
    class Program
    {
        const string INPUT_FILENAME = @"c:\temp\test.xml";
        const string OUTPUT_FILENAME = @"c:\temp\test1.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(INPUT_FILENAME);
            XmlWriter writer = XmlWriter.Create(OUTPUT_FILENAME);
            doc.WriteTo(writer);
            writer.Flush();
            writer.Close();
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM