Maison  >  Questions et réponses  >  le corps du texte

Analyser des chaînes HTML en Java : comment procéder

<p>Étant donné la chaîne "<table><tr><td>Hello World!"</td></tr></table>", obtenez le ( Quelle est la méthode la plus simple ? </p>
P粉193307465P粉193307465445 Il y a quelques jours522

répondre à tous(2)je répondrai

  • P粉731861241

    P粉7318612412023-08-02 14:55:30

    Si vous avez une chaîne contenant du HTML, vous pouvez utiliser la bibliothèque Jsoup comme ceci pour récupérer les éléments 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>

    répondre
    0
  • P粉176980522

    P粉1769805222023-08-02 00:57:10

    J'ai trouvé ça quelque part (je ne me souviens plus où) :

    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;
    }

    répondre
    0
  • Annulerrépondre