2009-09-30 6 views

Répondre

1

J'ai trouvé cela quelque part (ne me souviens pas 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; 
} 
3

You could use Swing:

Comment comptez-vous faire usage des capacités de traitement HTML qui sont construit en Java? Vous ne pouvez pas savoir que Swing contient toutes les classes nécessaires pour analyser HTML. Jeff Heaton vous montre comment.

6

Vous pouvez utiliser l'analyseur HTML, une bibliothèque Java utilisée pour analyser le code HTML de manière linéaire ou imbriquée. Il est un outil open source et se trouve sur SourceForge

3

Je l'ai utilisé Jericho HTML Parser il est OSS, Détecte (pardons) balises mal formaté et est léger

9

Voici un moyen:

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

Et si je veux mettre toutes les données dans un tableau de la classe externe plutôt que de les imprimer? – CodyBugstein

+0

@Imray, allez-y, vous avez la permission de les mettre dans une sorte de collection au lieu de les imprimer :) –

+0

Je les ai mises dans une collection à l'intérieur de la classe 'HTMLTableParser', puis j'ai créé une méthode getter pour les obtenir. Est-ce la meilleure façon de le faire? – CodyBugstein

5

Si vous avez une chaîne qui contient HTML, vous pouvez utiliser Jsoup bibliothèque comme ceci pour obtenir des é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> 

Bonne chance!

+0

Cette bibliothèque fait simplement le travail, merci! – negstek

Questions connexes