0

这是相关的(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)。

4

1 回答 1

2

您只能在调试时看到这些字符。我猜目的是您可以复制整个字符串并将其直接插入到 C# 代码中以进行进一步测试。此外,它能够将整个字符串表示为一行。

但是,\n当您访问代码中的字符串时,所有的 ' 都将转换为真正的换行符。所以你可以安全地解析它。

PS你为什么要手动调用网络请求?如果您在解决方案树中使用“添加 Web 引用”功能,Visual Studio 将为您生成存根代码。然后您不必关心 XML - 您将使用 Visual Studio 根据 WSDL 描述生成的对象。

于 2012-04-16T14:12:21.133 回答