如何在Java中解析HTML字符串?

时间:2009-09-30 13:00:09

标签: java html parsing

给定字符串"<table><tr><td>Hello World!</td></tr></table>",获得DOM元素代表它的(最简单)方法是什么?

7 个答案:

答案 0 :(得分:9)

这是一种方式:

import java.io.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

public class HtmlParseDemo {
   public static void main(String [] args) throws Exception {
       Reader reader = new StringReader("<table><tr><td>Hello</td><td>World!</td></tr></table>");
       HTMLEditorKit.Parser parser = new ParserDelegator();
       parser.parse(reader, new HTMLTableParser(), true);
       reader.close();
   }
}

class HTMLTableParser extends HTMLEditorKit.ParserCallback {

    private boolean encounteredATableRow = false;

    public void handleText(char[] data, int pos) {
        if(encounteredATableRow) System.out.println(new String(data));
    }

    public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
        if(t == HTML.Tag.TR) encounteredATableRow = true;
    }

    public void handleEndTag(HTML.Tag t, int pos) {
        if(t == HTML.Tag.TR) encounteredATableRow = false;
    }
}

答案 1 :(得分:7)

如果你有一个包含HTML的字符串,你可以使用这样的Jsoup库来获取HTML元素:

String htmlTable= "<table><tr><td>Hello World!</td></tr></table>";
Document doc = Jsoup.parse(htmlTable);

// then use something like this to get your element:
Elements tds = doc.getElementsByTag("td");

// tds will contain this one element: <td>Hello World!</td>
祝你好运!

答案 2 :(得分:6)

您可以使用HTML Parser,Java库用于以线性或嵌套方式解析HTML。 它是一个开源工具,可以在SourceForge上找到

答案 3 :(得分:3)

You could use Swing:

  

你如何利用   HTML处理功能   内置于Java?你可能不知道   Swing包含所有类   解析HTML所必需的。杰夫希顿   告诉你如何。

答案 4 :(得分:3)

我使用了Jericho HTML Parser它的OSS,检测(原谅)格式错误的标签并且是轻量级的

答案 5 :(得分:1)

我在某个地方找到了这个(不记得在哪里):

 public static DocumentFragment parseXml(Document doc, String fragment)
 {
    // Wrap the fragment in an arbitrary element.
    fragment = "<fragment>"+fragment+"</fragment>";
    try
    {
        // Create a DOM builder and parse the fragment.
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document d = factory.newDocumentBuilder().parse(
                new InputSource(new StringReader(fragment)));

        // Import the nodes of the new document into doc so that they
        // will be compatible with doc.
        Node node = doc.importNode(d.getDocumentElement(), true);

        // Create the document fragment node to hold the new nodes.
        DocumentFragment docfrag = doc.createDocumentFragment();

        // Move the nodes into the fragment.
        while (node.hasChildNodes())
        {
            docfrag.appendChild(node.removeChild(node.getFirstChild()));
        }
        // Return the fragment.
        return docfrag;
    }
    catch (SAXException e)
    {
        // A parsing error occurred; the XML input is not valid.
    }
    catch (ParserConfigurationException e)
    {
    }
    catch (IOException e)
    {
    }
    return null;
}

答案 6 :(得分:0)

可以使用一些 javax.swing.text.html 实用程序类来解析 HTML。

import java.io.IOException;
import java.io.StringReader;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
//...
try {
    String htmlString = "<html><head><title>Example Title</title></head><body>Some text...</body></html>";
    HTMLEditorKit htmlEditKit = new HTMLEditorKit();
    HTMLDocument htmlDocument = (HTMLDocument) htmlEditKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    parser.parse(new StringReader(htmlString),
            htmlDocument.getReader(0), true);
    // Use HTMLDocument here
    System.out.println(htmlDocument.getProperty("title")); // Example Title
} catch(IOException e){
    //Handle
    e.printStackTrace();
}

见:

相关问题