您需要IElementHandler
在自己的类中实现接口:
public class SampleHandler : IElementHandler {
//Generic list of elements
public List<IElement> elements = new List<IElement>();
//Add the supplied item to the list
public void Add(IWritable w) {
if (w is WritableElement) {
elements.AddRange(((WritableElement)w).Elements());
}
}
}
这里没有使用文件流,而是解析字符串的示例。要使用文件,请将 替换StringReader
为StreamReader
.
string html = "<html><head><title>Test Document</title></head><body><p>This is a test. <strong>Bold <em>and italic</em></strong></p><ol><li>Dog</li><li>Cat</li></ol></body></html>";
//Instantiate our handler
var mh = new SampleHandler();
//Bind a reader to our text
using (TextReader sr = new StringReader(html)) {
//Parse
XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr);
}
//Loop through each element
foreach (var element in mh.elements) {
//Loop through each chunk in each element
foreach (var chunk in element.Chunks) {
//Do something
}
}