XmlSerializer 一个具有多个类属性的类
目标:序列化 ClassMain 的所有公共属性:
public class ClassMain
{
ClassA classA = new ClassA();
public ClassMain()
{
classA.Prop1 = "Prop1";
classA.Prop2 = "Prop2";
}
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public ClassA ClassA
{
get
{
return classA;
}
}
}
ClassA:
public class ClassA
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
这就是我序列化的方式:
private void button1_Click(object sender, EventArgs e)
{
ClassMain classMain = new ClassMain();
classMain.Prop1 = "Prop1";
classMain.Prop2 = "Prop2";
XmlSerializer mySerializer = new XmlSerializer(typeof(ClassMain));
StreamWriter myWriter = new StreamWriter("xml1.xml");
mySerializer.Serialize(myWriter, classMain);
myWriter.Close();
}
在本例中,xml 输出为:
<?xml version="1.0" encoding="utf-8"?>
<Prop1>Prop1</Prop1>
<Prop2>Prop2</Prop2>
</ClassMain>
如您所见,缺少 ClassA 属性。
有人可以帮我吗?
问候
Objective: Serialize all the public properties of the ClassMain:
public class ClassMain
{
ClassA classA = new ClassA();
public ClassMain()
{
classA.Prop1 = "Prop1";
classA.Prop2 = "Prop2";
}
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public ClassA ClassA
{
get
{
return classA;
}
}
}
ClassA:
public class ClassA
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
This is how i´m serializing:
private void button1_Click(object sender, EventArgs e)
{
ClassMain classMain = new ClassMain();
classMain.Prop1 = "Prop1";
classMain.Prop2 = "Prop2";
XmlSerializer mySerializer = new XmlSerializer(typeof(ClassMain));
StreamWriter myWriter = new StreamWriter("xml1.xml");
mySerializer.Serialize(myWriter, classMain);
myWriter.Close();
}
In this case, the xml output is:
<?xml version="1.0" encoding="utf-8"?>
<ClassMain xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Prop1>Prop1</Prop1>
<Prop2>Prop2</Prop2>
</ClassMain>
As you see, is lacking the ClassA properties.
Can anyone help me out?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仅当属性同时具有 getter 和 setter 时,才会包含在 Xml 序列化中,大概是因为此规则确保序列化可以往返,即如果没有 setter,您将无法反序列化将 Xml 返回到目标对象中。
您的 ClassA 属性没有 setter。
Properties will only be included in Xml serialization if they have both a getter and a setter, presumably as this rule ensures that serialization can round-trip i.e. if there is no setter, you would not be able to deserialize the Xml back into the target object.
Your ClassA property has no setter.