我正在与REST服务集成,到目前为止一切都很好。遇到了一点障碍。我正在通过HttpWebRequest访问服务。我正在成功地接收响应,但是在通过StreamReader运行HttpWebResponse GetResponseStream时,我得到了一个
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">427</int>.在如何将其转换回c#整型上有点卡住了。
有什么建议吗?
谢谢。
发布于 2012-01-17 07:02:14
您可以将int.Parse和int.TryParse方法与XDocument结合使用,您可以使用它将响应XML加载到:
var request = WebRequest.Create(...);
...
using (var response = request.GetResponse())
using (var stream = response.GetStream())
{
var doc = XDocument.Load(stream);
if (int.TryParse(doc.Root.Value, out value))
{
// the parsing was successful => you could do something with
// the integer value you have just read from the body of the response
// assuming the server returned the XML you have shown in your question,
// value should equal 427 here.
}
}或者更简单的是,XDocument的Load方法可以理解HTTP,所以您甚至可以这样做:
var doc = XDocument.Load("http://foo/bar");
if (int.TryParse(doc.Root.Value, out value))
{
// the parsing was successful => you could do something with
// the integer value you have just read from the body of the response
// assuming the server returned the XML you have shown in your question,
// value should equal 427 here.
}这样,您甚至不需要使用任何HTTP请求/响应。一切都将由BCL为您处理,这是一件很棒的事情。
发布于 2012-01-17 07:02:22
如果您只是尝试将字符串"427“转换为int,则使用Int32.Parse方法。
var str = "427";
var number = Int32.Parse(str); // value == 427 https://stackoverflow.com/questions/8887491
复制相似问题