2011-12-13 194 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

我沒有去了解如何把一個換行符在評論上述... –