我的HTML树中有类似下面的内容。我想通过迭代div来创建一个JSON,记住data-view
是哪个父data-view
的实际孩子。最终结果将类似于{"main":{"header":{"navbar":"some txt","static":"some text"},"slider":"some txt","footer":"some txt"}}
<div id="loader-div"></div>
<div class="main-container">
<div data-view="main" data-class="main_class">
<div class="details_container">
<h1>Helo Text</h1>
<div data-view="header" data-class="header_class">
<h2>Hello Header</h2>
<div data-view="navbar" data-class="navbar_class">
<h2>sdf</h2>
<span data-text="navbarDataId">some text</span>
</div>
<div class="brder_bttm clearfix">
<div data-view="static" data-class="static_class">
<span data-text="navbarDataId">some text</span>
<button data-event="show_all" class="btn btn-block btn-success">Show All</button>
</div>
</div>
<span>some text</span>
</div>
<div class="slider_container">
<div data-view="slider" data-class="slider_class">
<span data-text="sliderDataId">some text</span>
</div>
</div>
<div data-view="footer" data-class="footer_class">
<span data-text="footerDataId">some text</span>
</div>
</div>
</div>
</div>
我试过了
for (int z = 0; z < doc.getElementsByAttributeStarting("data-view").size(); z++ ){
String dtview= doc.getElementsByAttributeStarting("data-view").get(z).attr("mt-class")
}
但这给了我所有的孩子元素,却无法找到哪个孩子属于哪个孩子?如果通过其他图书馆可以实现同样的目标,我很高兴能够开启它。 更新:更新了我的html以了解具体情况。请注意,
答案 0 :(得分:1)
是的,你可以使用Jsoup来做到这一点。我创建了一个递归方法,将被调用以从HTML动态生成JSON。
package com.github.davidepastore.stackoverflow38395047;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* Stackoverflow 38395047 answer.
*
*/
public class App {
public static void main(String[] args) {
String html = "<div data-view=\"main\">\r\n"
+ " <div data-view=\"header\">\r\n"
+ " <div data-view=\"navbar\">\r\n"
+ " <span>some text</span>\r\n"
+ " </div>\r\n" + " <span>some text</span>\r\n"
+ " </div>\r\n" + " <div data-view=\"slider\">\r\n"
+ " <span>some text</span>\r\n" + " </div>\r\n"
+ " <div data-view=\"footer\">\r\n"
+ " <span>some text</span>\r\n" + " </div>\r\n"
+ "</div>";
JSONObject json = new JSONObject();
Document document = Jsoup.parse(html);
Element body = document.select("body").first();
json = (JSONObject) generateJson(body);
System.out.println(json.toString(2));
}
public static Object generateJson(Element element){
JSONObject json = new JSONObject();
Elements children = element.children();
for (Element child : children) {
if(child.tagName().equals("div")){
String dataView = child.attr("data-view");
json.put(dataView, generateJson(child));
} else if(json.keySet().size() == 0){
return child.text();
}
}
return json;
}
}
输出:
{"main": {
"footer": "some text",
"slider": "some text",
"header": {"navbar": "some text"}
}}