这是相关的(C#.NET)代码:
WebRequest webRequest = System.Net.WebRequest.Create(authenticationUrl);
UTF8Encoding encoding = new UTF8Encoding();
...
var webResponse = webRequest.GetResponse();
var webResponseLength = webResponse.ContentLength;
byte[] responseBytes = new byte[webResponseLength];
webResponse.GetResponseStream().Read(responseBytes, 0, (int)webResponseLength);
var responseText = encoding.GetString(responseBytes);
webResponse.Close();
下面是responseText
的值(在调试上述代码时从 Visual Studio 复制):
"<?xml version="1.0" encoding="utf-8"?>n<responseblock version="3.67">n <requestreference>X3909254</requestreference>n <response type="ERROR">n <timestamp>2012-04-16 13:53:59</timestamp>n <error>n <message>Invalid field</message>n <code>30000</code>n <data>baseamount</data>n </error>n </response>n</responseblock>n"
为什么似乎有转义字符(例如 "
) 在响应中?这是由于我将响应流转换为字符串的方式吗?我应该怎么做(以便存储在变量responseText
中的值可以解析为"标准"XML)?
更新 – 我正在使用的更多代码:
var resultXML = XElement.Parse(responseText);
...
int errorCode = (int)(resultXML.Element("error").Element("code"));
问题是元素error
不是resultXML
根元素的直接子元素,因此我显然无法引用error
(或其子元素code
)。
只有在调试时才能看到这些字符。我想目的是您可以复制整个字符串并将其直接插入 C# 代码以进行进一步测试。此外,它能够将整个字符串表示为一行。
但是,当您访问代码中的字符串时,所有n
都将转换为实际换行符。因此,您可以安全地解析它。
附言为什么要手动调用 Web 请求?如果您使用解决方案树中的"添加 Web 引用"功能,Visual Studio 将为您生成存根代码。然后,您不必关心XML-您将使用Visual Studio基于WSDL描述生成的对象。