问题:
提取两个标头之间的所有html,包括标头html。标题文本是已知的,但不是格式,标记名称等。它们不在同一个父级中,并且可能(好吧,几乎可以肯定)在其自己的子级中有子子项。)
澄清:标题可以位于<h1>
或<div>
或任何其他标记内。它们也可能被<b>
,<i>
,<font>
或更多<div>
个标记所包围。关键是:元素中唯一的文本是标题文本。
我可用的工具是:使用WebBrowser控件的C#3.0,或Jquery / Js。
我已经采用Jquery路径,遍历DOM,但我遇到了孩子们的问题,并适当地添加它们。这是迄今为止的代码:
function getAllBetween(firstEl,lastEl) {
var collection = new Array(); // Collection of Elements
var fefound =false;
$('body').find('*').each(function(){
var curEl = $(this);
if($(curEl).text() == firstEl)
fefound=true;
if($(curEl).text() == lastEl)
return false;
// need something to add children children
// otherwise we get <table></table><tbody></tbody><tr></tr> etc
if (fefound)
collection.push(curEl);
});
var div = document.createElement("DIV");
for (var i=0,len=collection.length;i<len;i++){
$(div).append(collection[i]);
}
return($(div).html());
}
我应该继续走这条路吗?使用某种递归函数检查/处理子项,还是一种全新的方法更适合?
为了测试,这里有一些示例标记:
<body>
<div>
<div>Start</div>
<table><tbody><tr><td>Oops</td></tr></tbody></table>
</div>
<div>
<div>End</div>
</div>
</body>
非常感谢任何建议或想法!
答案 0 :(得分:1)
我的想法是一个正则表达式,类似于
.*<(?<tag>.+)>Start</\1>(?<found_data>.+)<\1>End</\1>.*
应该可以获得Start和end div标签之间的所有内容。
答案 1 :(得分:0)
这是一个想法:
$(function() {
// Get the parent div start is in:
var $elie = $("div:contains(Start)").eq(0), htmlArr = [];
// Push HTML of that div to the HTML array
htmlArr.push($('<div>').append( $elie.clone() ).html());
// Keep moving along and adding to array until we hit END
while($elie.find("div:contains(End)").length != 1) {
$elie = $elie.next();
htmlArr.push($('<div>').append( $elie.clone() ).html());
};
// htmlArr now has the HTML
// let's see what it is:
alert(htmlArr.join(""));
});
这会占用div
所在的整个父start
。我不确定这是你想要的。 outerHTML由$('<div>').append( element.clone() ).html()
完成,因为outerHTML支持尚未跨浏览器。所有的html都存储在一个数组中,你也可以只将元素存储在数组中。