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

5ssjco0h  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(333)

我正在尝试从带有原始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来获取/删除元素。

bxfogqkk

bxfogqkk1#

jsoup本机支持一组css选择器,而不是xpath。你可以这样做:

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

(请参阅选择器语法和元素#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);

相关问题