哪个库允许我对html字符串计算xpath?
我尝试过使用javax包,但似乎失败了:
String docroot = "<div><i>items <b>sold</b></i></div>";
XPath xxpath = XPathFactory.newInstance().newXPath();
InputSource docroot = new InputSource(new StringReader(subelements));
String result = (String) xxpath.evaluate("//b", docroot, XPathConstants.STRING);
发布于 2010-12-02 14:37:32
请尝试以下操作,因为您的代码示例中存在一些错误:
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) throws Exception {
String docroot = "<div><i>items <b>sold</b></i></div>";
XPath xxpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = new InputSource(new StringReader(docroot));
String result = (String) xxpath.evaluate("//b", inputSource, XPathConstants.STRING);
System.out.println(result);
}
}
发布于 2010-12-01 22:11:07
您需要一个足够宽松的解析器来将HTML解析为XML,这是很少见的。我相信TagSoup - http://java-source.net/open-source/html-parsers/tagsoup -可以做到这一点,但我已经很久没有看过它了。
(更多信息请点击:http://java-source.net/open-source/html-parsers/tagsoup)
有什么理由不能只提供XHTML代码片段吗?
发布于 2010-12-01 22:15:41
您需要一个能够生成有效XML文档对象的Java HTML解析库。基于这种不科学的library comparison,HTML Cleaner似乎可以做到这一点。
从HTML Cleaner站点:
虽然主要目的是准备普通的超文本标记语言,以便使用XPath、XQuery和XSLT进行处理,但是HtmlCleaner产生的结构化数据也可以通过菜单中的其他方式使用和处理。
此documentation link提供了一个示例,说明如何读入HTML字符串、执行XPath查询以及处理结果。
https://stackoverflow.com/questions/4329630
复制相似问题