我正在尝试编写一个程序来将对象序列化为xml文件。
[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 };
}
这是我要序列化的对象类。
我用来序列化的代码是
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();
我得到的XML是
<?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>
但我应该有
<?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>
你能告诉我我做错了什么,我是XML和序列化的新手。
答案 0 :(得分:2)
您的_location
字段似乎是私有的。 XML序列化只会序列化公共属性和字段。尝试将其包装在公共财产中。