我不得不在最近的項目中這樣做,我使用LINQ to XML。如果你知道它始終是乾淨的XHTML,那麼你可以很容易遞歸地複製DOM,但是我使用DevComponents HTMLDocument類庫(http://www.devcomponents.com/htmldoc/)將HTML轉換爲XML,然後將其轉換爲XElement。這可以減少將您的HTML轉換爲XElement層次結構的難題。一個警告是它腳本元素扼殺,所以我通過蠻力刪除這些。
/// <summary>
/// Extracts an HtmlDocument DOM to an XElement DOM that can be queried using LINQ to XML.
/// </summary>
/// <param name="htmlDocument">HtmlDocument containing DOM of page to extract.</param>
/// <returns>HTML content as <see cref="XElement" /> for consumption by LINQ to XML.</returns>
public XElement ExtractXml(HtmlDocument htmlDocument) {
XmlDocument xmlDoc = htmlDocument.ToXMLDocument();
// Find and remove all script tags from XML DOM or LINQ to XML will choke on XElement.Parse(XmlDocument).
IList<XmlNode> nodes = new List<XmlNode>();
foreach (XmlNode node in xmlDoc.GetElementsByTagName("script"))
nodes.Add(node);
foreach (XmlNode node in nodes)
node.ParentNode.RemoveChild(node);
return XElement.Parse(xmlDoc.OuterXml);
}
過得好的HTML?通過網頁瀏覽器控件,或通過HttpRequest,或...? – 2009-02-12 16:51:55
嗨,我通過HttpRequest獲取HTML。 – 2009-02-12 16:57:10