使用带有多个类的类序列化为xml
本文关键字:序列化 xml | 更新日期: 2023-09-27 18:14:20
我正在使用asp.net和c#来序列化一些使用类输入的数据。这个类是从一个xsd文件生成的。我使用这个类来生成一个xml文件。我正在努力理解如何引用所有这些类并将其序列化到一个xml文件。
这是我的类代码。它在我的项目中的一个单独的文件中:
namespace Ce
{
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.33440.
//
public partial class AddRequest
{
private CDocument cDocumentField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "x")]
public CDocument CDocument
{
get
{
return this.cDocumentField;
}
set
{
this.cDocumentField = value;
}
}
}
public partial class CDocument
{
private CaseA caseAField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "x")]
public CaseA CaseA
{
get
{
return this.caseAField;
}
set
{
this.caseAField = value;
}
}
}
public partial class CaseA
{
public string dCTextField;
private string dLField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "x")]
public string DCText
{
get
{
return this.dCTextField;
}
set
{
this.dCTextField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "x")]
public string DLU
{
get
{
return this.dLField;
}
set
{
this.dLField = value;
}
}
}
}
为了序列化,我在我的代码后面有一个按钮单击事件:
protected void CaseSubmitButton_Click(object sender, EventArgs e)
{
CaseA CSerialize = new CaseA();
CSerialize.DCText = casetextboxt.text;
CSerialize.DLu = "''app";
XmlSerializer Serializer = new XmlSerializer(typeof(CaseA));
StreamWriter Writer = new StreamWriter(Server.MapPath("~/XmlPackages/" + xmlPackageFilename));
Serializer.Serialize(Writer, CSerialize);
Serializer.Serialize(Writer, CSerialize);
}
通过这个按钮点击事件,我得到这个xml格式:
<?xml version="1.0" encoding="utf-8"?>
<CaseA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DCText>'apptest</DCText>
<DLU>'apptest</DLU>
</CaseA>
我想引用其他两个类来获得:
<?xml version="1.0" encoding="utf-8"?>
<Addrequest>
<Cdocument>
<CaseA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DCText>'apptest</DCText>
<DLU>'apptest</DLU>
</CaseA>
</Cdocument>
</Addrequest>
您正在序列化CaseA
类的实例,这就是为什么您只在输出中看到CaseA
的成员。您需要创建AddRequest
的实例并将其序列化为根,如下所示:
CaseA cSerialize = new CaseA();
cSerialize .DCText = casetextboxt.text;
cSerialize .DLu = "''app";
CDocument document = new CDocument();
document.CaseA = cSerialize ;
AddRequest root = new AddRequest();
root.CDocument = document;
XmlSerializer serializer = new XmlSerializer(typeof(AddRequest), new Type[] { typeof(CDocument), typeof(CaseA) });
StreamWriter writer = new StreamWriter(Server.MapPath("~/XmlPackages/" + xmlPackageFilename));
serializer.Serialize(writer, root);
作为旁注,请遵循c#命名本地变量的编码标准:)