[英]How do I parse a HTML string to split by parent div's?
所以我有一個像下面這樣的html字符串:
<div class="row xyz">
<!--Multiple Other div's and tags-->
</div>
<div class="row xws">
<!--Multiple Other div's and tags-->
</div>
<div class="row daze">
<!--Multiple Other div's and tags-->
</div>
你可以看到它有3個父div !
如何將我的HTML字符串與JAVA分開父div的數量,而不使用動態生成的類名“row xyz”,在這種情況下為3我將得到:
字符串div1
字符串div2
字符串div3
其中div1 =
<div class="row xyz">
<!--Multiple Other div's and tags-->
</div>
和
div2 =
<div class="row xws">
<!--Multiple Other div's and tags-->
</div>
和
div3 =
<div class="row daze">
<!--Multiple Other div's and tags-->
</div>
嘗試使用如下的jsoup :
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class MyClass {
public static void main(String args[]) {
String html = "<html><head/><body>"+
"<div class=\"row xyz\"> <div>div1</div> <div>div1_1</div> </div>"+
"<div class=\"row xws\"> <div>div2</div> </div>" +
"<div class=\"row daze\"> <div>div3</div></div>"+
"</body></html>";
Document document = Jsoup.parse(html);
Elements divs = document.select("body > div");//get first level of divs
for (int i=0; i< divs.size(); i++) {
System.out.println(String.format("div%d = %s", i + 1, divs.get(i).outerHtml()));
}
}
}
輸出將是:
div1 = <div class="row xyz">
<div>
div1
</div>
<div>
div1_1
</div>
</div>
div2 = <div class="row xws">
<div>
div2
</div>
</div>
div3 = <div class="row daze">
<div>
div3
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.