views:

49

answers:

2

I am trying a write a program to serialize a object to a xml file.

   [XmlRoot ("Person")]
    public class person
    {
        [XmlElement("Name")]
        public string name { get; set; }
        [XmlElement("Age")]
        public int age { get; set; }
        [XmlElement ("Location")]
        location _location = new location { city = "Delhi", country = "India", distance = 123 };
    }

This is the class which object I want to serialize.

The code I am using to serialze is

 person _person = new person { name = "ASDF", age = 25};
            System.Xml.Serialization.XmlSerializer XS = new System.Xml.Serialization.XmlSerializer(typeof(person));
            System.IO.TextWriter TW = new System.IO.StreamWriter(System.IO.File.Create("C:\\Users\\vaibhav.1.jain\\Documents\\Visual Studio 2010\\Projects\\LinqWeb\\LinqWeb\\xmlser\\ser4.xml"));
            XS.Serialize(TW, _person);
            TW.Close();

And the XML I am getting is

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Name>ASDF</Name>
  <Age>25</Age>
</Person>

But I should have got

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Name>ASDF</Name>
  <Age>25</Age>
  <location>
    <country>India</country>
    <city>Delhi</city>
    <distance>12</distance>
  </location>
</Person>

Can you tell me what I am doing wrong, I am new to XML and serialization.

+2  A: 

It looks like your _location field is private. XML serialization will only serialize public properties and fields. Try wrapping it in a public property.

Evgeny
perfect it worked, But I dont want to make it _location a public field. Do we have some alternative for it.
vaibhav
As I said, you can wrap it in a public property. But one way or another, it must be publicly accessible for XML serialization to work with it.
Evgeny
+1  A: 

you can use DataContractSerializer.

Check this out http://stackoverflow.com/questions/802711/serializing-private-member-data

Hammad Rajjoub