如何使用 X-Path 解析对 JSON 的 HTML 响应?
Posted
技术标签:
【中文标题】如何使用 X-Path 解析对 JSON 的 HTML 响应?【英文标题】:How do I parse an HTML response to JSON by using X-Path? 【发布时间】:2018-05-22 11:56:37 【问题描述】:我收到了来自 HTTPGET
方法的 html 响应。如何解析对 JSON 的 html 响应?
我使用哪个 API 来解析它?
我也想知道x-path
的主要用途是什么。
HTML 响应:
<!DOCTYPE html> <[if IE 8]> <html lang="en" class="ie ie8 lt-ie9 lt-ie10"> <![endif]> <[if IE 9]> <html lang="en" class="ie ie9 lt-ie10"> <![endif]> <if IE]> <html lang="en" class="ie"> <![endif] <[if gt IE 9]> <html lang="en"> <![endif] <head prefix="og: ogp.me/ns# fb: ogp.me/ns/fb# snapdeallog:#"> <link rel="dns-prefetch" href="i1.sdlcdn.com"; />
【问题讨论】:
你的 HTML 响应是什么样的? 看起来像:您可以使用jsoup 作为工具将您的 HTML 转换为 JSON。
final String HTML = "<!DOCTYPE html> <[if IE 8]> <html lang="en" class="ie ie8 lt-ie9 lt-ie10"> <![endif]> <[if IE 9]> <html lang="en" class="ie ie9 lt-ie10"> <![endif]> <if IE]> <html lang="en" class="ie"> <![endif] <[if gt IE 9]> <html lang="en"> <![endif] <head prefix="og: ogp.me/ns# fb: ogp.me/ns/fb# snapdeallog:#"> <link rel="dns-prefetch" href="i1.sdlcdn.com"; />";
Document document = Jsoup.parse(HTML);
Element element = document.select("ANY HTML TAG").first();
String arrayName = element.select("TAG2").first().text();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
Elements ie = element.getElementsByClass("ie");
Elements ei9 = element.getElementsByClass("ei9");
JSONObject jobj = new JSONObject();
for (int i = 0, l = ie.size(); i < l; i++)
String key = ie.get(i).text();
String value = ei9.get(i).text();
jobj.put(key, value);
jsonArr.put(jobj);
jsonObj.put(arrayName, jsonArr);
System.out.println(jsonObj.toString());
【讨论】:
以上是关于如何使用 X-Path 解析对 JSON 的 HTML 响应?的主要内容,如果未能解决你的问题,请参考以下文章
XSD 中的 X-Path 2.0 (assert): "count(//elem/text() = 'test') > 0" 始终为真,即使字符串不匹配