简体   繁体   English

使用XmlSerializer时自动缩小属性/元素名称

[英]Automatically minifying attribute/element names when using XmlSerializer

When serializing a C# class using XmlSerializer, the attributes/elements representing the properties of the class will have the same names as they do in the source code. 使用XmlSerializer序列化C#类时,表示类属性的属性/元素将与源代码中的名称/名称相同。

I know you can override this by doing like so: 我知道您可以这样做,以覆盖此问题:

[XmlAttribute("num")]
public int NumberOfThingsThatAbcXyz { get; set; }

I'd like the generated XML for my classes to be as compact as possible, but obviously still capable of being automatically deserialized on the other side. 我希望为我的类生成的XML尽可能紧凑,但显然仍然能够在另一侧自动反序列化。

Is there a way to have these names minified as much as possible without having to manually think of and annotate everything with a short string? 有没有一种方法可以尽可能地缩小这些名称,而不必用短字符串手动思考和注释所有内容? The resultant XML being easily human readable isn't a concern. 生成的XML易于人类阅读不是问题。

Hmya, watch out for micro-optimizations like this. 嗯,请提防此类微优化。 It is incredibly hard to make them pay off with modern computing hardware. 要用现代计算硬件来回报他们是很难的。 The true cost of the I/O involved with handling XML is not the amount of data, it is locating it. 处理XML所涉及的I / O的真正成本不是数据量,而是它的位置。 Bytes are cheap, transmitting them is highly optimized already. 字节便宜,传输字节已经高度优化。 It is a disk drive read head grinding away on a server somewhere, perhaps on your own machine, that determines how fast your program runs. 它是磁盘驱动器读头在服务器上(可能是您自己的计算机上)磨掉的,它决定了程序的运行速度。 Once it is in the right spot, reading a byte is very nearly as expensive as reading a kilobyte. 一旦到达正确的位置,读取一个字节与读取一个千字节几乎一样昂贵。 Memory works the same way. 内存的工作方式相同。

The ultimate hint: if it would be a common optimization, they would have come up with something better than IXmlSerializable. 最终提示:如果这是一个常见的优化,那么他们会提出比IXmlSerializable更好的东西。

为了在使用属性的基础上自定义XML序列化,您将需要您的类来实现IXmlSerializable接口。

If human readability isn't an issue... why use xml at all - perhaps something like "protocol buffers" (there are C# implementations available) will give you the desired level of interoperability without this issue, including some ways of getting all the properties automatically (I can talk more about this if you are interested). 如果可读性是不是一个问题?为什么使用XML 的话 -或许像“协议缓冲区”(有可用的C#实现)会给你的互操作性的理想水平,而不该问题,包括获取的一些方法全部自动设置属性(如果您有兴趣的话,我可以讨论更多)。

Another alternative is simply to gzip the data; 另一种选择是简单地gzip压缩数据。 xml zips surprising well, thanks to all the repeated node names. 由于所有重复的节点名称,xml zip压缩得非常好。

The nature of attributes implies that this can't be done. 属性的性质意味着无法做到这一点。 See can-attributes-be-added-dynamically-in-c# for why. 有关为什么原因,请参见可以在c#中动态添加属性 Even if it could be done, I agree with Hans that it probably isn't worth it. 即使可以做到,我也同意汉斯的说法,这可能不值得。 If you are really concerned about this then you should go with one of Marc's suggestions. 如果您真的对此感到担心,那么您应该选择Marc的建议之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM