我使用以下代码将 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("&nbsp", " "); // MARK 2
responseXhtml.LoadXml(responseString);
return responseXhtml;

MARK 1 行用于跳过 DOC 类型定义行。

MARK 2 行是为了避免错误 Reference to undeclared entity 'nbsp'

有没有更好的方法来做到这一点?上面代码中的字符串操作太多了。

谢谢!

最佳答案

我会直接使用 HtmlAgilityPack 来解析 html。即使你必须将html转换为xml,你也可以使用它。

using (WebClient wc = new WebClient())
{
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(wc.DownloadString("http://www.google.com"));
    doc.OptionOutputAsXml = true;

    StringWriter writer = new StringWriter();
    doc.Save(writer);

    var xDoc = XDocument.Load(new StringReader(writer.ToString()));
}

关于c# - XmlDocument 无法加载 XHTML 字符串,因为错误 "Reference to undeclared entity ' nbsp'",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12822680/

10-11 12:38