.NET XmlSerializer:如何替换 xml 标签的名称?
对于某些数据导出,我们所做的只是使用 XmlSerializer 序列化 .Net 对象,例如列表或集合。我们使用这样的东西:
public static bool WriteToXMLFile(string fullFileNameWithPath, Object obj, Type ObjectType)
{
TextWriter xr = null;
try
{
XmlSerializer ser = new XmlSerializer(ObjectType);
xr = new StreamWriter(fullFileNameWithPath);
ser.Serialize(xr, obj);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(xr != null)
xr.Close();
}
return true;
}
对于类型的列表,生成的 XML 类似于以下片段:
<ArrayOfMyObjects>
<MyObject>
//content here
</MyObject>
</ArrayOfMyObjects>
但另一边的期望(该文件的接收者是这样的:
<MT_MyObjects>
<MyObject>
//content here
</MyObject>
</MT_MyObjects>
那么我如何将 ArrayOfMyObjects 更改为 MT_MyObjects,同时序列化?我知道也可以使用一些 Regx 替换来完成,但我不想稍后再修改
输出:
我最终可以这样解决问题:
[Serializable]
[XmlRoot("MT_LoadProfile")]
public class LoadProfArray : List<LoadProfile>
{
//....
}
For some data export, what we are doing is just serializing the .Net objects like a list or Collection using XmlSerializer. We use something like this:
public static bool WriteToXMLFile(string fullFileNameWithPath, Object obj, Type ObjectType)
{
TextWriter xr = null;
try
{
XmlSerializer ser = new XmlSerializer(ObjectType);
xr = new StreamWriter(fullFileNameWithPath);
ser.Serialize(xr, obj);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(xr != null)
xr.Close();
}
return true;
}
For a list of a type, the XML that is generated comes like the following segment:
<ArrayOfMyObjects>
<MyObject>
//content here
</MyObject>
</ArrayOfMyObjects>
But the expectation on the other side (receiver of this file is something like this:
<MT_MyObjects>
<MyObject>
//content here
</MyObject>
</MT_MyObjects>
So how can I change ArrayOfMyObjects to MT_MyObjects while serializing? I know it can be done using some Regx replacement also. But I wanted not to touch the output later.
Update: The solution:
I could solve the issue finally like this:
[Serializable]
[XmlRoot("MT_LoadProfile")]
public class LoadProfArray : List<LoadProfile>
{
//....
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于序列化数组,您可以定义控制对象序列化方式的属性。但是,如果对象是列表,则需要创建一个类并继承它,然后定义属性:
这将创建以下输出:
For serialising Arrays, you can define attributes which governs how an object is serialised. However if the object is a list, you need to create a class and inherit from it and then define the attributes:
This will create this output:
在你的班级中,用
In your class, decorate the property with
请查找下面的示例:
/步骤1/
其集合要被序列化的虚拟类
/Step2/
创建列表集合并应用 XMLRootElement
/步骤 3/
用数据填充 MyObject 类并序列化
Please Find The Example below:
/Step1/
The Dummy Class whose collection was to be serialised
/Step2/
Create a List Collection and Apply The XMLRootElement
/Step3/
Populate the MyObject Class with Data and serialise