在原始列表上使用 DataContractSerializer 的自定义元素名称 [英] Custom Element Names using the DataContractSerializer on a List of primitives

查看:26
本文介绍了在原始列表上使用 DataContractSerializer 的自定义元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在 DataContractSerializer 中使用原始元素列表时设置自定义元素名称的最佳方法感兴趣.假设我有以下类,其中包含一个字符串列表作为 DataMember.

I'm interested about the best way to go about setting custom element names when using List of primitives with the DataContractSerializer. Let's say I have the following class which contains a List of Strings as a DataMember.

[DataContract]
public class ClassName
{
    [DataMember]
    public List<String> FieldName { get; set; }
}

默认情况下,这会序列化为以下内容:

By default, this serializes to the following:

<ClassName xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <FieldName xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <a:string>Value 1</a:string>
    <a:string>Value 2</a:string>
    <a:string>Value 3</a:string>
  </FieldName>
</ClassName>

我想让 XML 尽可能简单地通过 XSLT 进行转换,因此理想情况下,我会将标签重命名为更有用的名称,例如 Value.

I would like to make the XML as simple as possible to transform via XSLT so ideally I would rename the tags into something more useful, like Value.

一种可能的解决方案是创建一个扩展 Collection 的类并为 CollectionDataMember 参数设置 ItemName,我发现它此处.我想知道是否有一种方法可以在不需要这个额外的类或其他形式的包装类的情况下实现相同的目标.XML 序列化程序使用 XMLArray 和 XMLArrayItem 参数来完成此操作,但 DataContractSerializer 似乎没有类似的功能.

One possible solution involves creating a class that extends Collection and setting the ItemName for the CollectionDataMember parameter, which I found here. I was wondering if there was a way to accomplish the same goal without the need for a this extra class or other form of wrapper class. The XML serializer makes use of XMLArray and XMLArrayItem parameters to accomplish this but the DataContractSerializer does not appear to have similar functionality.

感谢您提供任何提示或想法!

Thanks for any tips or ideas!

推荐答案

定义数据协定以表示字符串列表并将其用作 FieldName 属性的类型.然后你可以使用 CollectionDataContract 属性来自定义 XML.

Define data contract to represent list of strings and use it as a type for your FieldName property. Then you can use CollectionDataContract attribute to customize XML.

[CollectionDataContract(ItemName="Value")]
public class MyList : List<string>  {}

[DataMember]
public MyList FieldName { get; set; }

这篇关于在原始列表上使用 DataContractSerializer 的自定义元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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