【发布时间】:2019-08-08 14:03:15
【问题描述】:
我向演示 API 发送了 XML 帖子,响应以 XML 流的形式返回,如下所示:
API=3CProductData&XML=%3CProductData+Name%3D%22NameTest%22%3E%0D%0A++%3CId%3EXXXXXXXXX%3C%2FId%3E%0D%0A%3C%2FProductData%3E
我猜这就是流的样子,我的目标是获取该响应并将其存储在一个新的 ProductData 对象中,这是我目前所做的:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
// as an xml: deserialise into your own object or parse as you wish
StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
string receivedResponse = respStream.ReadToEnd();
XmlSerializer x = new XmlSerializer(typeof(ProductData));
ProductData product = (ProductData) x.Deserialize(new StringReader(receivedResponse));
Console.WriteLine("Node1: " + product.Id.ToString());
Console.WriteLine("Node2: " + product.Name);
Console.ReadKey();
}
错误返回 System.InvalidOperationException:“XML 文档 (0, 0) 中存在错误。” XmlException: 缺少根元素。
【问题讨论】:
-
那是您的实际响应正文吗?还是来自查询字符串的数据?
-
它的查询字符串也不应该是响应
-
@Jesse de Wit 我还定制了响应给我一个 XML 但仍然是同样的问题?
-
那是一些糟糕的 XML。 Name 节点不会自行关闭。恐怕您将不得不手动处理此响应。
-
查询字符串是(请求的)url 的一部分。 http 响应消息由状态码、标头和响应正文组成。在此处发布状态代码和响应正文,我们可能会提供帮助。 (将响应正文作为字符串读取并在调试器中检查)