我会在 Javascript 中使用匿名函数来解析表格并将内容作为字符串数组返回。这将更容易在 C# 中解析。
有关在 Javascript 中解析表的示例,请参见http://jsfiddle.net/stevejansen/xDZQP/ 。(旁注:我会检查您的数据源是否提供 REST API 或类似的来访问这些数据;解析 HTML 真的很脆弱。)
这大致就是我将 C# 和 JS 结合起来解决您的问题的方式(C# 未经测试)。请注意,您使用了错误的返回类型IWebView.ExecuteJavascriptWithResult
。
const string JAVASCRIPT = @"(function () {
var table = document.getElementById('production_table'),
records = [];
if (table == null) return;
table = table.getElementsByTagName('tbody');
if (table == null || table.length === 0) return;
// there should only be one tbody element in a table
table = table[0];
// getElementsByTagName returns a NodeList instead of an Array
// but we can still use Array#forEach on it
Array.prototype.forEach.call(table.getElementsByTagName('tr'),
function (row) {
var record = [];
Array.prototype.forEach.call(row.getElementsByTagName('td'),
function (cell) {
record.push(cell.innerText);
});
records.push(record);
});
return records;
})();";
JSValue result = view.ExecuteJavascriptWithResult(JAVASCRIPT);
JSValue[] records;
JSValue[] record;
if (result.IsNull || !result.IsArray)
return;
records = (JSValue[])result;
foreach(JSValue row in records)
{
if (row == null || row.IsNull || !row.IsArray)
continue;
record = (JSValue[])row;
foreach(JSValue cell in record)
{
if (cell.IsNull || !cell.IsString)
continue;
System.Diagnostics.Debug.WriteLine((string)cell);
}
}