1

I'm running the following code:

public String Serialize()
{
  XmlSerializer serializer = new XmlSerializer(typeof(SomeInformation));
  StringWriter writer = new StringWriter();
  serializer.Serialize(writer, new SomeInformation());
  String output = writer.ToString();
  return output;
}

With the serialization as follows.

[XmlRoot("MyRoot")]
public class SomeInformation
{
  public SomeInformation() { }

  [XmlElement("SomeNode1")]
  public String Prop1 { get { return "Some prop 1"; } }

  [XmlElement("SomeNode2")]
  public String Prop2 { get { return "Some prop 2"; } }
}

I'm getting the string to contain an XML but with no inner tags. I'm new to serialization and totally stuck. Any suggestions on what I'm doing wrong?!

  • See [the documentation](http://msdn.microsoft.com/en-us/library/hf00byt3.aspx): "Apply the XmlElementAttribute to **public fields** or **public read/write properties**" – mellamokb Mar 19 '13 at 17:32
  • possible duplicate of [Why are properties without a setter not serialized](http://stackoverflow.com/questions/13401192/why-are-properties-without-a-setter-not-serialized) – mellamokb Mar 19 '13 at 17:33
  • 1
    @mellamokb My formulation is better. In order to find **that** other question one has to know that the setters missing are the problem. And by then, one knows the answer. –  Mar 19 '13 at 18:02

3 Answers3

2

XmlSerializer does not serialize read-only properties. Try adding empty setter to them.

For more details take a look at: Why are properties without a setter not serialized

Community
  • 1
  • 1
alex
  • 12,464
  • 3
  • 46
  • 67
  • I got it. Finally. I had removed the setters because I had another issue before. For some reason, I can't serialize e.g. *Uri* instances. Only string. Any suggestions on that? –  Mar 19 '13 at 18:01
2

It doesn't make sense to serialize read only properties. I would make Prop1 and Prop2 read/write properties and set them in code.

Paul Keister
  • 12,851
  • 5
  • 46
  • 75
1

You're using read-only properties. Don't.

I just ran your class with the addition of empty setter and I get the data in the string.

[XmlRoot("MyRoot")]
public sealed class SomeInformation
{
  public SomeInformation() { }

  [XmlElement("SomeNode1")]
  public String Prop1 { get { return "Some prop 1"; } set { } }

  [XmlElement("SomeNode2")]
  public String Prop2 { get { return "Some prop 2"; } set { } }
}
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438