views:

23

answers:

1

Hi, I want to serialize my object to xml and then to a string.

  public class MyObject
  {
    [XmlElement]
    public string Name
    [XmlElement]
    public string Location;
  }

I want to obtain a single line string which will lok like this:

<MyObject><Name>Vladimir</Name><Location>Moskov</Location></MyObject>

I am using such code:

  XmlWriterSettings settings = new XmlWriterSettings();
  settings.OmitXmlDeclaration = true;
  settings.Indent = true;
  StringWriter StringWriter = new StringWriter();
  StringWriter.NewLine = ""; //tried to change it but without effect
  XmlWriter writer = XmlWriter.Create(StringWriter, settings);
  XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  namespaces.Add(string.Empty, string.Empty);
  XmlSerializer MySerializer= new XmlSerializer(typeof(MyObject ));
  MyObject myObject = new MyObject { Name = "Vladimir", Location = "Moskov" };

  MySerializer.Serialize(writer, myObject, namespaces);
  string s = StringWriter.ToString();

This is the closest what I get:

<MyObject>\r\n  <Name>Vladimir</Name>\r\n  <Location>Moskov</Location>\r\n</MyObject>

I do know that I could remove "\r\n" from the string afterwards. But I would like to not produce them at all rather than removing them later.

Thanks for your time.

+1  A: 

You could try:

settings.NewLineHandling = NewLineHandling.None;
settings.Indent = false;

which for me, gives:

<MyObject><Name>Vladimir</Name><Location>Moskov</Location></MyObject>
Marc Gravell
Thanks Mark, it works. Thanks for correction in topic too.
Wodzu