javaandroidhtmlsaxparser

get body content of html file in java


i'm trying to get body content of html page.

suppose this html file:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <link href="../Styles/style.css" rel="STYLESHEET" type="text/css" />

  <title></title>
</head>

<body>
<p> text 1 </p>
<p> text 2 </p>
</body>
</html>

what i want is :

<p> text 1 </p> 
<p> text 2 </p>

so, i thought that using SAXParser would do that (if you know simpler way please tell me)

this is my code, but always i get null as body content:

private final String HTML_NAME_SPACE = "http://www.w3.org/1999/xhtml";
private final String HTML_TAG = "html";
private final String BODY_TAG = "body";
public static void parseHTML(InputStream in, ContentHandler handler) throws IOException, SAXException, ParserConfigurationException
{
    if(in != null)
    {
        try
        {
            SAXParserFactory parseFactory = SAXParserFactory.newInstance();
            XMLReader reader = parseFactory.newSAXParser().getXMLReader();
            reader.setContentHandler(handler);
            InputSource source = new InputSource(in);
            source.setEncoding("UTF-8");
            reader.parse(source);
        }
        finally
        {
            in.close();
        }
    }
}

public ContentHandler constrauctHTMLContentHandler()
{
    RootElement root = new RootElement(HTML_NAME_SPACE, HTML_TAG);
    root.setStartElementListener(new StartElementListener() 
        {           
        @Override
        public void start(Attributes attributes) 
        {           
            String body = attributes.getValue(BODY_TAG);
            Log.d("html parser", "body: " + body);
        }
    });
return root.getContentHandler();
}

then

parseHTML(inputStream, constrauctHTMLContentHandler()); // inputStream is html file as stream

what is wrong with this code?


Solution

  • How about using Jsoup? Your code can look like

    Document doc = Jsoup.parse(html);
    Elements elements = doc.select("body").first().children();
    //or only `<p>` elements
    //Elements elements = doc.select("p"); 
    for (Element el : elements)
        System.out.println("element: "+el);