Vaibhav Jain
Vaibhav Jain

Reputation: 34417

Help needed in XML Serialization

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

Upvotes: 1

Views: 306

Answers (1)

EMP
EMP

Reputation: 62011

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

Upvotes: 2

Related Questions