开发者

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.Cr开发者_如何学Ceate("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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜