使用XMLWorker将HTML转换为列表
本文关键字:列表 转换 HTML XMLWorker 使用 | 更新日期: 2023-09-27 18:03:21
是否有人可以提供一个使用XMLWorkerHelper在iTextSharp (c#)中将HTML解析为元素列表的示例。
文档中给出的JAVA版本是:
XMLWorkerHelper.getInstance().parseXHtml(new ElementHandler() {
public void add(final Writable w) {
if (w instanceof WritableElement) {
List<Element> elements = ((WritableElement)w).elements();
// write class names of elements to file
}
}
}, HTMLParsingToList.class.getResourceAsStream("/html/walden.html"));
您需要在自己的类中实现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
}
}