Creating an HTMLDocument from an HTML string (in Java)

I am working on a method that takes an HTML string and returns a similar

javax.swing.text.html.HTMLDocument 

What is the most efficient way to do this?

The way I'm doing it now is to use the SAX parser to parse an HTML string. I track when I click open tags (e.g. <i>). When I click on the appropriate closing tag (e.g. </i>), I apply the italic style to the characters I hit between them.

It certainly works, but it is not fast enough. Is there a faster way to do this?

+6
source share
3 answers

Try using the HtmlEditorKit class. It supports parsing HTML content that can be read directly from String (e.g. via StringReader ). There seems to be an article on how to do this.

Edit: To give an example, basically I think it could be done as follows (aftrer, code executed, htmlDoc should contain the loaded document ...):

 Reader stringReader = new StringReader(string); HTMLEditorKit htmlKit = new HTMLEditorKit(); HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument(); HTMLEditorKit.Parser parser = new ParserDelegator(); parser.parse(stringReader, htmlDoc.getReader(0), true); 
+4
source

Agree with the mouser, but a little correction

 Reader stringReader = new StringReader(string); HTMLEditorKit htmlKit = new HTMLEditorKit(); HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument(); htmlKit.read(stringReader, htmlDoc, 0); 
+8
source

You can try using the HTMLDocument.setOuterHTML method. Just add a random element and replace it with your HTML string.

0
source

Source: https://habr.com/ru/post/892784/


All Articles