2011-12-13 211 views
5

我有以下的HTML如何替换元素?

<html> 
<head> 
    <title>test</title> 

</head> 
<body> 
    <table> 
    <caption>table title and/or explanatory text</caption> 
    <thead> 
    <tr> 
    <th>header</th> 
</tr> 
</thead> 
<tbody> 
     <tr> 
     <td id=\"test\" width=\"272\"></td> 
</tr> 
</tbody> 
</table> 
<a href=\"http://www.google.fi\" style=\"color:black\">Test link</a> 
<a href=\"http://www.google.fi\"><img src=\"http://www.google.se/images/nav_logo95.png\" /></a>" 
</body> 
</html>; 

而且我想找到jsoup第一环节,并用文字代替它

Element elem = page.select("a[href=" + link.getUrl() + "]:contains(" + link.getName() + ")").first(); 

我只能elem.html("foo")替换内部HTML或打印outerHtml与elem.outerHtml()

有谁知道我该如何做到这一点?

回答

13

我找到了答案!

TextNode text = new TextNode("foo", ""); 
elem.replaceWith(text); 
0

一旦你找到你要使用的元素,你可以申请的命令如这里解释:http://jsoup.org/cookbook/modifying-data/set-html

我无法得到它的权利。我想这一点:

elemento.prepend("<a href='www.test.com'>");  
elemento.html("Roberto C. Santos.");     
elemento.append("</a>"); 
elemento.wrap("<a href='www.test.com'> </a>"); 

但我得到这个:

<td><a href="www.test.com"> <a style="" target="_self" title="" href="http://ivv.veveivv.vvzenes.com.br/mao/ara/ccacao" data-mce-href="resolveuid/5cc1c7c8c9efcacaaeedec22a9c69a54" class="internal-link">Roberto C. Santos.</a></a></td> 
    </tr> 

我还是鸵鸟政策知道,以便交换URL元素的内容具体的方式。

我倒是想有,作为结果:

<a href='www.test.com'> Roberto C. Santos.</a>" 

如何coul'd擦除HREF是其间的?

+0

我所做的事情不对,就是得到了错误的元素。到目前为止,我发现选择正确的元素的最佳方式是遍历所有元素。如果还没有找到确切的循环,嵌套循环会有所帮助。例如: for(Element elem:contElems){if(elem.id()!=“”)System.out.println(elem.id()); \t 元素contElems1 = contElems.select(“href,a [href],a [data-href],link [href],a [title]”); 为(元素elem1:contElems1){// 把代码在这里 } // (或/和)把代码在这里 } –

+0

我没有去了解如何把一个换行符在评论上述... –