-1

I am trying to generate an XML file from an Object. I put a break point before generating the XML file, so I can check the values. The object and its value look fine. However, after the XML file is generated, it is missing a key component, the code.

This is what I was expected to see.

<eDocument Code="UN" Cat="ST">                          
  <id myId="5"/>
</eDocument>

This is the actual xml file that is generated.

<eDocument Cat="EST">                          
  <id myId="5"/>
</eDocument>

This is the object that is being serialize to generate the xml file.

sDoc eDocument = new sDoc();
eDocument.Code = "UN";
eDocument.Cat = "ST";
eDocument.myId = new ID[1];
eDocument.myId[0].id= 5;

This is how I am saving the file

 string fileName= "student.xml";
 XmlSerializer serializeObject = new XmlSerializer(eDocument.GetType());
 TextWriter streamWritter = new StreamWriter(Server.MapPath(@"~/student/" + fileName));
 serializeObject.Serialize(streamWritter, eDocument); // I check the eDocument Object, and it has all the correct inforamtion
 streamWritter.Close();

Is there something that I am doing wrong here?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user3802347
  • 108
  • 1
  • 10

1 Answers1

2

You need to check the "Code" property in the sDoc class.

A property should be public read/write in order to be Xml-serializable. By default, if no attribute is applied to a public property, it is serialized as an XML element. In your case it's not serialized at all, which means something is wrong.

First check: is the property public in both read (get) and write (set)?

Second check: Isn't the field marked with [XmlIgnoreAttribute]?

And finally: Marking the Cat property with [XmlAttribute] will xml-serialize it as an attribute.

msporek
  • 1,187
  • 8
  • 21
  • After reading your comment, I check my properties again. It was adding an additional attributes [System.ComponentModel.DefaultValueAttribute("UN")]. I removed it, and the code works fine. – user3802347 Dec 19 '14 at 23:22
  • Good to know, that's something I wouldn't be able to guess ;-). – msporek Dec 19 '14 at 23:23