Java 使用JSOUP节点获取元素内容';s属性
我和JSoup有麻烦 我有以下html代码:Java 使用JSOUP节点获取元素内容';s属性,java,html,Java,Html,我和JSoup有麻烦 我有以下html代码: <div title = "test" data-x="test1">I am the content</div> 我可以通过打印看到,Jsoup假定元素内容是一个属性。是这样吗? 在这个例子中,我只希望得到“title”和“data-x” 谢谢你试试这个 String html = "<div title = 'test' data-x='test1'>I am the content</div>
<div title = "test" data-x="test1">I am the content</div>
我可以通过打印看到,Jsoup假定元素内容是一个属性。是这样吗?
在这个例子中,我只希望得到“title”和“data-x”
谢谢你试试这个
String html = "<div title = 'test' data-x='test1'>I am the content</div>";
Document doc = Jsoup.parse(html);
Element div = doc.select("div").first();
String divTitle = div.attr("title"); // "test"
String divDataX = div.attr("data-x"); // "test1"
String html=“我就是内容”;
Document doc=Jsoup.parse(html);
Element div=doc.select(“div”).first();
字符串divTitle=div.attr(“title”);//“测试”
字符串divDataX=div.attr(“data-x”);//“测试1”
当您遍历某个节点时,NodeVisitor也会访问其内容,将其视为文本类型的子节点。可以使用深度变量过滤出节点属性
Document doc = Jsoup.parse(data);
doc.getElementsByTag("div").traverse(new NodeVisitor() {
public void head(Node node, int depth) {
System.out.println(depth + ":" + node.attributes());
}
public void tail(Node node, int depth) {
}
});
输出如下:
0: title="test" data-x="test1"
1: #text="I am the content"
因此,在head()方法中添加深度检查:
public void head(Node node, int depth) {
if(depth == 0) {
Attributes attributes = node.attributes();
// handle attributes
}
}
谢谢,但我不能让它静止。我需要迭代节点的属性
public void head(Node node, int depth) {
if(depth == 0) {
Attributes attributes = node.attributes();
// handle attributes
}
}