首页 > 社区问答列表 >在Java中解析HTML字符串:如何做

  在Java中解析HTML字符串:如何做

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

P粉193307465
P粉193307465

  • P粉731861241
  • P粉731861241     2023-08-02 14:55:30 2楼

    如果你有一个包含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>

    +0 添加回复

  • P粉176980522
  • P粉176980522   已被采纳   2023-08-02 00:57:10 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;
    }

    +0 添加回复