如何使DataContractSerializer XML更具可读性? [英] How can I make DataContractSerializer XML more readable?

查看:85
本文介绍了如何使DataContractSerializer XML更具可读性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将复杂的数据结构序列化为XML.

I want to serialize a complex data structure to XML.

对象具有其他对象的列表/字典,而列表/字典本身可能具有其他对象的列表/字典.

Objects have lists / dictionaries of other objects that might have lists / dictionaries of other objects themselves.

通常,我只会使用DataContractSerializer,但是它会产生难看的,难以理解的XML,而且杂乱无章,某些XML标签后面有任意字符(

Generally I'd just use the DataContractSerializer but it produces ugly, hard to read XML with weird clutter, some XML tags have arbitrary characters after them (KeyValueOfstringChildB5f9yUGrh) and if you remove that clutter the XML is no longer recognized by the DataContractSerializer.

我尝试改用XMLSerializer,但由于某种原因它无法序列化字典.

I tried using an XMLSerializer instead but it cannot serialize dictionaries for whatever reason.

如何创建带有字典的易于理解的复杂类的XML序列化?

How can I create an easily readable XML serialization of complex classes with dictionaries?

是否固定"了DataContractSerializer的XML或使用XMLSerializer来序列化字典.

Whether it's "fixing" the  DataContractSerializer's XML or making it possible to serialize dictionaries with the XMLSerializer.

推荐答案

您正在使用多个泛型类型,因为生成器无法生成类似Key< string>并且有多个会发生冲突.如果要使用更简洁的名称,则可以为泛型创建派生类型. 那应该可以解决该问题,但是,当然,可以添加仅用于序列化的冗余类型.

You'll get the ugly names whenever you're using multiple generic types because the generator cannot generate something like Key<string> and having multiple ones would conflict. If you want cleaner names then create derived types for your generics. That should resolve the issue but, of course, adds redundant types that are just for serialization.

串行化实际上并不是为了美观和可读性而设计的.它旨在来回获取数据.您可以使用属性(例如,DataMember)来控制某些命名,以使其更具可读性,因此我将从此开始.如果那还没把你带到哪里 然后,您可能只需要实现必要的接口即可自己序列化数据并放弃数据合同. XML格式对于浪费"垃圾邮件非常重要.时间来做到这一点.

Serialization isn't really designed to be pretty and readable. It's designed to get data back and forth. You can use attributes (eg. DataMember) to control some of the naming to make it more readable so I'd start with that. If that doesn't get you where you want then you might just need to implement the necessary interface(s) to serialize the data yourself and forego data contracts. The XML formatting would need to be pretty important to "waste" time doing that though.

迈克尔·泰勒
http://www.michaeltaylorp3.net

Michael Taylor
http://www.michaeltaylorp3.net


这篇关于如何使DataContractSerializer XML更具可读性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆