使用 jsoup 或任何其他库通过原始 xpath 从 HTML 中删除元素

Delete element from HTML by raw xpath using jsoup or any other library

提问人:mwKART 提问时间:12/3/2020 更新时间:1/9/2021 访问量:171

问:

我正在尝试从具有原始 xpath 的 HTML 中删除元素。

        final Document document = Jsoup.parse(htmlAsString);
        final Elements elements = document.select("/html/head");
        elements.forEach(Node::remove);

但是遇到了以下错误,

org.jsoup.select.Selector$SelectorParseException: Could not parse query '/html/head': unexpected token at '/html/head'
at org.jsoup.select.QueryParser.findElements(QueryParser.java:206)
at org.jsoup.select.QueryParser.parse(QueryParser.java:59)
at org.jsoup.select.QueryParser.parse(QueryParser.java:42)
at org.jsoup.select.Selector.select(Selector.java:91)
at org.jsoup.nodes.Element.select(Element.java:372)

有没有办法从html处理原始xpath来获取/删除元素。

java spring-boot xpath jsoup html 解析

评论


答:

0赞 Jonathan Hedley 1/9/2021 #1

jsoup 原生支持一组 CSS 选择器,而不是 xpath。你可以这样做:

Document doc = Jsoup.parse(html);
document.select("html > head").remove();

(请参阅 Selector 语法Elements#remove() 文档。

如果你需要专门使用 xpath(为什么?),你可以使用 jsoup 的 W3C Dom 转换器将 jsoup 文档转换为 W3C 文档 (Java XML),并针对它运行 xpath 查询:

import org.w3c.dom.Document;
import org.w3c.dom.Node;
...

org.jsoup.nodes.Document jdoc = Jsoup.parse(html);
Document w3doc = W3CDom.convert(jdoc);

String query = "/html/head";
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile(query);
Node head = (Node) xpath.evaluate(w3doc, XPathConstants.NODE);

评论

1赞 mwKART 1/22/2021
我使用了CSS选择器。最初的要求是具有 xpath。但后来为了简单起见,我改变了要求。