Questo semplice argomento riguarda come convertire HTML in testo in Java. In Java HTML in testo normale è possibile sviluppare applicazioni di conversione in esecuzione su piattaforme Windows, Linux o macOS utilizzando interfacce API semplici e facili.
Passaggi per convertire HTML in testo in Java
- Configura il tuo progetto per aggiungere Aspose.HTML for Java dal repository Maven
- Includi il riferimento allo spazio dei nomi Aspose.HTML nella tua applicazione
- Leggere il contenuto del file HTML di origine utilizzando l’oggetto String
- Inizializza l’oggetto HTMLDocument class per caricare la stringa HTML di origine
- Inizializza l’oggetto della classe INodeIterator per iterare i nodi e aggiungerli in StringBuilder
- Salva il testo estratto dall’HTML su disco
Per estrarre testo da HTML Java è possibile utilizzare un’applicazione basata su poche righe di codice. Inizieremo il processo caricando l’HTML sorgente in un oggetto String e successivamente caricando quella String usando la classe HTMLDocument. Useremo quindi INodeIterator per estrarre, attraversare e aggiungere i nodi HTML a uno StringBuilder. Infine, lo StringBuilder verrà salvato come file di testo normale su disco.
Codice per convertire HTML in testo in Java
import com.aspose.html.HTMLDocument; | |
import com.aspose.html.License; | |
import com.aspose.html.dom.Node; | |
import com.aspose.html.dom.traversal.INodeIterator; | |
import com.aspose.html.dom.traversal.filters.NodeFilter; | |
import java.nio.file.Paths; | |
import java.nio.file.Files; | |
import java.io.IOException; | |
import java.nio.charset.Charset; | |
import java.nio.charset.StandardCharsets; | |
import java.util.stream.Collectors; | |
public class HtmlToTextCoverter { | |
public static void main(String[] argsHTMLFile) throws Exception { | |
// Setting Aspose.Html Java API license to use complete features | |
License lic = new License(); | |
lic.setLicense("HTML.Total.Java.lic"); | |
// Read the HTML file in String | |
String content = null; | |
try { | |
content = readFileContent("TestFile.html", StandardCharsets.UTF_8); | |
} catch (IOException exception) { | |
exception.printStackTrace(); | |
return; | |
} | |
// Instantiate HtmlDocument object to load HTML content in String | |
HTMLDocument document = new HTMLDocument(content, ""); | |
// Initialize INodeIterator instance iterate HTML nodes | |
INodeIterator iterator = document.createNodeIterator(document, NodeFilter.SHOW_TEXT, new StyleFilter()); | |
StringBuilder Stringbld = new StringBuilder(); | |
// Temp Node object | |
Node node; | |
// Iterate through Nodes | |
while ((node = iterator.nextNode()) != null) | |
Stringbld.append(node.getNodeValue()); | |
System.out.println(Stringbld.toString()); | |
Files.write(Paths.get("HtmlToText_Java.txt"), Stringbld.toString().getBytes()); | |
} | |
public static String readFileContent(String filePath, Charset encoding) throws IOException { | |
String fileContent = Files.lines(Paths.get(filePath), encoding) | |
.collect(Collectors.joining(System.lineSeparator())); | |
return fileContent; | |
} | |
} | |
class StyleFilter extends NodeFilter { | |
@Override | |
public short acceptNode(Node node) { | |
// In order to skip an element while fetching nodes, mention the name of element in upper case letters | |
return (node.getParentElement().getTagName() == "STYLE" || node.getParentElement().getTagName() == "SCRIPT" | |
? FILTER_REJECT : FILTER_ACCEPT); | |
} | |
} |
L’esempio sopra in Java converte l’HTML in testo normale in poche chiamate API. Abbiamo creato la classe StyleFilter che estende la classe NodeFilter e implementa il metodo AcceptNode per impostare i filtri dei nodi del cliente ed omettere i nodi indesiderati dall’HTML durante il processo di conversione.
In questo argomento, abbiamo esplorato come estrarre testo da HTML in Java. Se sei interessato alla conversione del file MD in formato XPS, passa all’argomento come converti Markdown in XPS usando Java.