CollectionDataContract具有额外属性

时间:2016-10-24 06:09:41

标签: c# .net wcf xml-parsing

我正在使用WCF中的列表。我想在客户端和服务器之间传递一个额外属性的列表。

需要输出

<NumbersList>
    <Count>2</Count> //Extra property to parse
    <Number>1</Number>
    <Number>2</Number>
</NumbersList>

所以我按照以下链接教程:http://www.borismod.net/2009/04/wcf-collectiondatacontract-and.html

我编写了以下代码来实现这一目标。

[MessageContract]
public class RequestResponse
{
    [MessageBodyMember(Name = "NumbersList")]
    public NumbersList NumbersList;
}

[DataContract]
public class NumbersList
{
    [DataMember]
    public int Count { get; set; }

    [DataMember]
    public Number Number { get; set; }
}

[CollectionDataContract(ItemName = "Number")]
public class Number : Collection<int>
{        
}

所以它给我这样的输出

<NumbersList>
    <Count>2</Count>
    <Number>
        <Number>1</Number>
        <Number>2</Number>
    </Number>
</NumbersList>

如果我将Count装饰的DataMember属性直接放在CollectionDataContract内,而不是WCF省略该属性。

再试一次:

[MessageContract]
public class RequestResponse
{
    [MessageBodyMember(Name = "NumbersList")]
    public Number NumbersList;
}

[CollectionDataContract(ItemName = "Number")]
public class Number : Collection<int>
{
    [DataMember]
    public int Count { get; set; } // This will be omited...
}

可以像这样给出输出

<NumbersList>
    <Number>
        <Number>1</Number>
        <Number>2</Number>
    </Number>
</NumbersList>

任何人都可以帮助我获得输出,如下所示:

需要输出

<NumbersList>
    <Count>2</Count>
    <Number>1</Number>
    <Number>2</Number>
</NumbersList>

1 个答案:

答案 0 :(得分:1)

在做完R&amp; D并在asp.net论坛上研究和发布我的查询后,我得到了解决方案。

在我的情况下,CollectionDataContract对我无效,为此,我必须使用XmlSerializerFormat

所以我像这样重写我的代码:

[MessageContract]
public class Messanger
{
    [MessageBodyMember]
    [XmlElement(ElementName = "NumbersList")]
    public NumbersList NumbersList;
}

[DataContract]
[XmlRoot(ElementName = "NumbersList")]
public class NumbersList
{
    [XmlElement(ElementName = "Count")]
    public int Count { get; set; }

    [XmlElement(ElementName = "Number")]
    public List<int> Number { get; set; }
}

它将为我生成XML:

<NumbersList>
    <Count>2</Count> //Extra property to parse
    <Number>1</Number>
    <Number>2</Number>
</NumbersList>

以下是论坛的链接:https://social.msdn.microsoft.com/Forums/vstudio/en-US/12ceeae4-0284-4a3b-a913-e69811f41b81/collectiondatacontract-with-the-extra-property?forum=wcf