如何控制 .NET DataContract 序列化,使其使用 XML 属性而不是元素? [英] How can you control .NET DataContract serialization so it uses XML attributes instead of elements?

查看:17
本文介绍了如何控制 .NET DataContract 序列化,使其使用 XML 属性而不是元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个标记为 DataContract 的类和一些用 DataMember 属性标记的属性,我可以轻松地将它序列化为 XML,但它会创建输出喜欢:

If I have a class marked as a DataContract and a few properties on it marked with DataMember attributes I can serialize it out to XML easily, but it would create output like:

<Person>
    <Name>John Smith</Name>
    <Email>john.smith@acme.com</Email>
    <Phone>123-123-1234</Phone>
</Person>

我更喜欢的是属性,比如...

What I would prefer is attributes, like...

<Person Name="John Smith" Email="john.smith@acme.com" Phone="123-123-1234" />

DataMember 属性允许我控制名称和顺序,但不能控制它是否被序列化为元素或属性.我环顾四周,发现了 DataContractFormatIXmlSerializable,但我希望有更简单的解决方案.

The DataMember attribute allows me to control the Name and Order but not whether it is serialized as an element or attribute. I have looked around and found DataContractFormat and IXmlSerializable but I am hoping there is there an easier solution.

最简单的方法是什么?

推荐答案

你不能用 DataContractSerializer;如果你想要属性,你需要使用 XmlSerializer 代替.使用 DataContractSerializer 类,允许使用更严格的 XML 规范子集,这可以提高性能并改进已发布服务的互操作性,但让您对 XML 格式的控制较少.

You can't do this with the DataContractSerializer; if you want attributes you need to use the XmlSerializer instead. With the DataContractSerializer class a more restrictive subset of the XML specification is permitted which improves performance, and improves the interoperability of published services, but gives you rather less control over the XML format.

如果您使用 WCF 服务,请查看 XmlSerializerFormatAttribute 允许您使用 XmlSerializer 进行序列化.

If you're using WCF services then take a look at XmlSerializerFormatAttribute which allows you to use the XmlSerializer for serialization.

这篇关于如何控制 .NET DataContract 序列化,使其使用 XML 属性而不是元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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