我有一个 WCF RESTful 服务,它应该将客户的姓名和姓氏作为 XML 响应返回,该服务的定义如下所示
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/GetNameAndSurname")]
string GetNameAndSurname();
我遇到的问题是返回的 XML 响应不像预期的那样在正常 XML 中,例如
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<Customer;
<Name>Andre</Name>
<SurnameName>Lombaard</SurnameName>
>
</string>
我不确定是服务以这种方式返回响应还是我正在读取数据的方式,只是为了提供信息,我包含了我用来读取下面响应的代码,
var request = HttpWebRequest.Create(url);
request.Method = "POST";
request.Timeout = 2 * 60 * 1000;
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
request.ContentType = "text/xml";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
dataStream.Flush();
var results = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
如何在不必对响应中收到的字符执行各种替换的情况下获得正常的 XML。
目前我用下面的代码替换字符。这并不理想
results = results.Replace("</string>", String.Empty);
results = results.Replace("<", "<");
results = results.Replace(">
", ">");
results = results.Replace(">", ">");
results = Regex.Replace(results, "<string .*?\\>", String.Empty);