同一C#DTO中的多个相同元素

时间:2016-04-27 13:24:53

标签: c# xml wcf

我正在尝试创建一个WCF服务,它可以返回一个类似这样的XML文档:

<alert>
    <identifier>SecretID</identifier>
    <info>
        <valueName>Name1</valueName>
        <value>Info1</value>
    </info>
    <info>
        <valueName>Name2</valueName>
        <value>Info2</value>
    </info>
</alert>

此文件的DTO看起来像这样:

[DataContract(Name = "alert", Namespace = "")]
public class Alert
{
    [DataMember(Name = "identifier")]
    public string identifier { get; set; }

    [DataMember(Name = "info")]
    public List<Info> Info { get; set; }
}

[DataContract(Name = "info", Namespace = "")]
public class Info
{
    [DataMember(Name = "valueName")]
    public string ValueName { get; set; }

    [DataMember(Name = "value")]
    public string Value { get; set; }
}

但是,当我尝试使用以下内容时:

var alert = new Alert()
{
    Identifier = "SecretID",
    Info = new List<Info>
    {
        new Info() {ValueName = "Name1", Value = "Info1"},
        new Info() {ValueName = "Name2", Value = "Info2"},
    }
}

我明白了:

<alert>
    <identifier>SecretID</identifier>
    <info>
        <info xmlns="">
            <valueName>Name1</valueName>
            <value>Info1</value>
        </info>
        <info xmlns="">
            <valueName>Name2</valueName>
            <value>Info2</value>
        </info>
    </info>
</alert>

我不需要额外的<info>标记,并且名称空间xmlns=""也很好。我该怎么做才能摆脱它?

1 个答案:

答案 0 :(得分:0)

您可以使用如下所述的字典或键值对:

[DataContract(Name = "alert", Namespace = "")]
public class Alert
{
    [DataMember(Name = "identifier")]
    public string identifier { get; set; }

    [DataMember(Name = "info")]
    public KeyValuePair<string, string> Info { get; set; }
}

var alert = new Alert()
{
    Identifier = "SecretID",
    Info = new KeyValuePair<string, string>()
}