数据契约序列化器 - 如何省略集合的外部元素
如何使用数据契约序列化程序序列化没有外部元素的列表?我正在使用.Net 3.5。我有一个类,其中包含一个列表,除其他外,我希望在没有外部元素的情况下序列化该列表,以便与相关的 XSD 兼容:
[DataContract(Name="MyClass")]
public class MyClass
{
...
[DataMember(Name="Parameters")]
public List<Parameter> Parameters;
...
}
[DataContract(Name="Parameter")]
public struct Parameter
{
[DataMember(Name="ValueName")]string ValueName;
[DataMember(Name="Value")]int Value;
public Parameter(string ValueName, int Value)
{
this.ValueName = ValueName;
this.Value = Value;
}
}
上面的序列化为(假设列表中只有一个参数):
<MyClass>
<Parameters>
<Parameter>
<ValueName></ValueName>
<Value></Value>
</Parameter>
</Parameters>
</MyClass>
我想序列化它如下所示:
<MyClass>
<Parameter>
<ValueName></ValueName>
<Value></Value>
</Parameter>
</MyClass>
使用 XmlSerializer 我可以通过将 [XmlElement] 应用于列表来做到这一点:
[XmlElement ("Parameter")]
public List<Parameter> Parameters;
但是我不想使用 XmlSerializer
因为我的类有一些不是序列化的属性友好,我希望能够处理那些使用 [OnSerializing] 系列属性的人。
谢谢。
How do I serialize a list without the outer element using the Data Contract Serializer? I am using .Net 3.5. I have a class that contains a list, amongst other things, that I wish to serialize without the outer element to be compliant with the pertinent XSD:
[DataContract(Name="MyClass")]
public class MyClass
{
...
[DataMember(Name="Parameters")]
public List<Parameter> Parameters;
...
}
[DataContract(Name="Parameter")]
public struct Parameter
{
[DataMember(Name="ValueName")]string ValueName;
[DataMember(Name="Value")]int Value;
public Parameter(string ValueName, int Value)
{
this.ValueName = ValueName;
this.Value = Value;
}
}
The above serializes as (assuming only one Parameter in the list):
<MyClass>
<Parameters>
<Parameter>
<ValueName></ValueName>
<Value></Value>
</Parameter>
</Parameters>
</MyClass>
I would like to serialize it as follows:
<MyClass>
<Parameter>
<ValueName></ValueName>
<Value></Value>
</Parameter>
</MyClass>
Using the XmlSerializer I can do this by applying the [XmlElement] to the list:
[XmlElement ("Parameter")]
public List<Parameter> Parameters;
However I do not want to use the XmlSerializer
because my class has a few properties that are not serialization friendly and I was hoping to deal with those using the [OnSerializing] family of attributes.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DataContract
序列化程序不允许对结果 XML 进行这种程度的控制,您必须改用XmlSerializer
才能实现此目的。The
DataContract
serializer does not allow this degree of control over the resulted XML, you will have to use instead theXmlSerializer
in order to achieve this.下面的代码使用 MessageContracts 进行工作,尽管这是一个“hack”——它将“MyClass”元素赋予 List 成员,并排除“MyClass”的包装器命名空间。
The below works using MessageContracts although is a 'hack' - it attributes the "MyClass" element to the List member and excludes the wrapper namespace for "MyClass".
使用集合数据协定:
这是实际的代码:
如果运行此代码,您将获得以下 XML:
Use a collection data contract:
Here is the actual code:
if you run this you will get the following XML: