我使用以下代码将 HTTP 响应流转换为 XmlDocument。
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
String responseString = responseReader.ReadToEnd();
Console.WriteLine(responseString);
Int32 htmlTagIndex = responseString.IndexOf("<html",
StringComparison.OrdinalIgnoreCase);
XmlDocument responseXhtml = new XmlDocument();
responseString = responseString.Substring(htmlTagIndex); // MARK 1
responseString = responseString.Replace(" ", " "); // MARK 2
responseXhtml.LoadXml(responseString);
return responseXhtml;
MARK 1行是跳过 DOC Type 定义行。
MARK 2行是为了避免错误Reference to undeclared entity 'nbsp'。
有没有更好的方法来做到这一点?上面代码中的字符串操作太多了。
谢谢!