2014-02-06 60 views
0

我是jsoup的新手,所以我對如何將修改應用到原始HTML文件並將其作爲輸出進行應用有點困惑。修改HTML文件,然後獲取修改後的html作爲輸出

在通過選擇html部分進行更改之後在通過選擇html

例如Element elements = doc.select("_____").attr("_____",____); (因爲這個元素只會有選定的部分...)

我該如何將這個應用到原始文檔?以便我可以將修改後的HTML作爲輸出?

非常感謝您

回答

2

這些更改將在您製作文檔時應用於文檔。例如,我開始了與此:

String html = "<html>" + 
     "<body>" + 
     "<p class=\"class1\">p1</p>" + 
     "<p class=\"class2\">p2</p>" + 
     "</body>" + 
     "</html>"; 

Document doc = Jsoup.parse(html); 
System.out.println(doc); 

它輸出:

<html> 
<head></head> 
<body> 
    <p class="class1">class1</p> 
    <p class="class2">class2</p> 
</body> 
</html> 

現在我做出一些改變到p元素:

Element p1 = doc.select("p.class1").first(); 
p1.attr("class", "classOne"); 

Element p2 = doc.select("p.class2").first(); 
p2.attr("id", "helloworld"); 

System.out.println(doc); 

的輸出是不同的,以反映我對它的元素所做的更改:

<html> 
<head></head> 
<body> 
    <p class="classOne">p1</p> 
    <p class="class2" id="helloworld">p2</p> 
</body> 
</html> 
+0

謝謝是非常好的答案 – user3278450