问题描述:

I have a WCF rest service. It has a method that returns a list of objects. The object type is set as a DataContract and it has DataMembers. Now it works great, I can get my list of objects as an XML via my method. It is great and nice.

My question is: is there any way to get result XML before returning it from the method? So, can I have exactly the same XML in my method as I can get when calling my method via REST?

.net4/vs2010

网友答案:

Alfonso's answer is somewhat right, but you mentioned you're using DataContract and DataMember. The XmlSerializer class is not meant to be used with data contracts. Instead what you're looking for is DataContractSerializer. Use of that is very similar, but would look like this instead:

DataContractSerializer serializer = new DataContractSerializer(typeof(YourResultType));
StringBuilder stringBuilder = new StringBuilder();

using(XmlWriter xmlWriter = XmlWriter.Create(stringBuilder))
{
    serializer.WriteObject(xmlWriter, someInstanceOfYourResultType);
}

// use stringBuilder.ToString() to get the XML
网友答案:

You could use XmlSerializer to save the result to a xml string before returning it.

XmlSerializer ser = new XmlSerializer(typeof(YourResultType));
StringBuilder sb = new StringBuilder();
StringWriter sw = new System.IO.StringWriter(sb);
ser.Serialize(sw, yourResult);
// Use sb.ToString()
相关阅读:
Top