需要通过使用DataContractSerializer来填充XML

时间:2014-11-12 18:43:00

标签: c# xml wcf datacontractserializer

我有一个方法将错误消息放入1 xml并将其发送到客户端。如果出现错误,错误可能有几个,我将返回XMLErrMessage中的列表错误。我想在评论中显示它们,但每个错误都是1 xml child:

  <comments>
     <comment>XMLErrMessage1</comment>
     <comment>XMLErrMessage2</comment>
    <comment>XMLErrMessage3</comment>
  </comments>

这是我的方法:

    public string ProcessXML(CommonLibrary.Model.TransferData dto, bool Authenticated)
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(CFCConnectResponse));
        MemoryStream ms = new MemoryStream();
        utility.utilities utl = new utility.utilities();
        List<string> XMLErrMessage =null;

        if (Authenticated)
        {
            if (!string.IsNullOrEmpty(dto.xml))
            {
                XMLErrMessage = utl.validateXML(dto.xml, xsdFilePath, currentSchema);

                if (XMLErrMessage.Count==1)
                {
                    dcs.WriteObject(ms, new CFCConnectResponse() { StatusCode = 101, StatusDescription = "Success" });
                    ms.Position = 0;
                }
                else
                {
                    dcs.WriteObject(ms, new CFCConnectResponse() { StatusCode = 201, StatusDescription = "XML Validation Fails", Comments=XMLErrMessage });
                    ms.Position = 0;
                }
            }
        }
        else
        {
            dcs.WriteObject(ms, new CFCConnectResponse() { StatusCode = 401, StatusDescription = "Authentication Fails" });
           // ms.Position = 0;
        }
        string s = new StreamReader(ms).ReadToEnd();  // xml result
        Console.WriteLine(s);
        return s;
    }

这是合同类:

public class CFCConnectResponse
{
    [DataMember]
    public int StatusCode;
    [DataMember]
    public string StatusDescription;
    [DataMember]
    public List<string> Comments;

1 个答案:

答案 0 :(得分:1)

CollectionDataContract属性允许您控制集合元素名称,但由于它只能定位类或结构,因此您必须使用所需的合同创建List<T>的自定义子类,如下所示:

[DataContract(Namespace = "")]
[KnownType(typeof(CommentList))]
public class CFCConnectResponse
{
    [DataMember]
    public int StatusCode;
    [DataMember]
    public string StatusDescription;
    [DataMember(Name="comments")]
    public CommentList Comments;
}

[CollectionDataContract(ItemName = "comment", Namespace="")]
public class CommentList : List<string>
{
    public CommentList()
        : base()
    {
    }

    public CommentList(params string[] strings)
        : base(strings)
    {
    }

    public CommentList(IEnumerable<string> strings)
        : base(strings)
    {
    }
}

然后,测试:

public static class TestCFCConnectResponse
{
    static CFCConnectResponse CreateTest()
    {
        return new CFCConnectResponse()
        {
            StatusCode = 101,
            StatusDescription = "here is a description",
            Comments = new CommentList("XMLErrMessage1", "XMLErrMessage2", "XMLErrMessage3"),
        };
    }

    public static void Test()
    {
        var response = CreateTest();

        try
        {
            var xml = DataContractSerializerHelper.GetXml(response);
            Debug.Write(xml);
            var newResponse = DataContractSerializerHelper.GetObject<CFCConnectResponse>(xml);
            Debug.Assert(newResponse != null);
            Debug.Assert(response.StatusCode == newResponse.StatusCode);
            Debug.Assert(response.StatusDescription == newResponse.StatusDescription);
            Debug.Assert(newResponse.Comments.SequenceEqual(response.Comments));
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }
    }
}

这会产生以下输出,没有断言:

<?xml version="1.0" encoding="utf-16"?>
<CFCConnectResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <StatusCode>101</StatusCode>
    <StatusDescription>here is a description</StatusDescription>
    <comments>
        <comment>XMLErrMessage1</comment>
        <comment>XMLErrMessage2</comment>
        <comment>XMLErrMessage3</comment>
    </comments>
</CFCConnectResponse>

<强>更新

如果要更改CFCConnectResponse.CommentList以获取&amp;设置CommentList需要对遗留代码进行太多更改,您可以执行以下操作:

[DataContract(Namespace = "")]
[KnownType(typeof(CommentList))]
public class CFCConnectResponse
{
    [DataMember]
    public int StatusCode;

    [DataMember]
    public string StatusDescription;

    [IgnoreDataMember]
    public List<string> Comments { get; set; }

    [DataMember(Name = "comments")]
    private CommentList SerializableComments
    {
        get
        {
            return new CommentList(Comments);
        }
        set
        {
            Comments = value.ToList();
        }
    }
}

这会保留List<string> Comments属性,同时序列化&amp;反序列化CommentList