如何控制.NET DataContract序列化,以便它使用XML属性而不是元素? [英] How can you control .NET DataContract serialization so it uses XML attributes instead of elements?
问题描述
如果我有标记为A类 DataContract
键,就可以了几个属性标记数据成员
属性,我可以轻松地将其序列化到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>
我会preFER的属性,如...
What I would prefer is attributes, like...
<Person Name="John Smith" Email="john.smith@acme.com" Phone="123-123-1234" />
在数据成员
属性可以让我控制名称和顺序,但不是它是否是序列化的元素或属性。我环顾四周,发现 DataContractFormat
和的IXmlSerializable
,但我希望有有更简单的解决方案。
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.
什么是做到这一点的最简单的方法是什么?
What is the easiest way to do this?
推荐答案
您不能做到这一点的的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服务,那么就来看看<一href="http://msdn.microsoft.com/en-us/library/system.servicemodel.xmlserializerformatattribute.aspx"><$c$c>XmlSerializerFormatAttribute$c$c>它允许您使用的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屋!