我刚开始探索Jsoup库,因为我将在我的项目中使用它。我试图通过谷歌搜索找到能帮助我的确切答案,但未能如愿。这是我的问题,我有一个包含以下元标记的HTML文件
<meta content="this is the title value" name="d.title">
<meta content="this is the description value" name="d.description">
<meta content="language is french" name="d.language">
以下是一个Java POJO的示例:
public class Example {
private String title;
private String description;
private String language;
public Example() {}
// setters and getters go here
}
现在我想解析HTML文件,提取d.title内容值并存储在Example.title中,提取d.description内容值并存储在Example.description中等等。
我通过阅读jsoup cookbook已经完成了一些工作,类似于:
Document doc = Jsoup.parse("test.html");
Elements metaTags = doc.getElementsByTag("meta");
for (Element metaTag : metaTags) {
String content = metaTag.attr("content");
String content = metaTag.attr("name");
}
那将会遍历所有元标签,获取它们的“content”和“name”属性的值,但我想要获取“name”属性为“d.title”的“content”属性的值,以便将其存储在Example.title中。更新:@P.J.Meisch下面的答案实际上解决了问题,但对于我来说那是太多的代码了(试图避免做完全相同的事情)。我的意思是,我认为可能可以像这样做:
String title = metaTags.getContent("d.title")
其中d.title是“name”属性的值。 这样将减少代码行数,我还没有找到这样的方法,但可能是因为我还是jsoup的新手,所以我问了。但是,如果不存在这样的方法(如果有这样的方法就太好了,因为它可以简化生活),我就会按照P.J.Meisch所说的去做。