我有一些复杂、肮脏的 html 代码。有没有一个好的 HTML 解析器可以让我将 HTML 代码用作 Java 对象?
例如我想访问此代码:
<html>
<body>
<div id='foo'>
<p id='bar'></p>
</div>
</body>
</html>
就像通过 DOM 一样:
[File/Code].getElementById('foo').appendText('bla');
[File/Code].getElement(Element.DIV).getElement(ELEMENT.P).getValue();
//etc...
有人有想法吗?
或者Java中有DOM(this does not help :()吗?
问候
最佳答案
只要给 http://jsoup.org/尝试一下。它可以处理非常损坏的 html。
示例:
public static void main(String[] args)
{
Document document = Jsoup.parse("<html>" +
" <body>" +
" <div id='foo'>" +
" <p id='bar'>TEST</p>" +
" </div>" +
" </body>" +
"</html>");
System.out.println("Add blah to the Element with ID: foo");
Element foo = document.getElementById("foo");
foo.appendText("blah");
System.out.println(document.html());
System.out.println("Get the content of a div having a p:");
for (Element div : document.getElementsByTag("div"))
{
for (Element p : div.getElementsByTag("p"))
{
System.out.println(p.text());
}
}
}
Maven
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.7.2</version>
</dependency>
关于Java HTML 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18046607/