How to write contents of Document Object to String in NekoHTML?

1k views Asked by At

I am using NekoHTML to parse contents of some HTML file..

Everything goes okay except for extracting the contents of the Document Object to some string.

I've tried uses

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);

But nothing appears returned.

2

There are 2 answers

0
Muhammad Hewedy On BEST ANSWER
0
David On

Posible solution:

//this nekohtml  
DOMParser parser = new DOMParser();  
parser.parse(archivo);  


//this xerces  
OutputFormat format = new OutputFormat(parser.getDocument());   
format.setIndenting(true);  

//print xml for console 
//XMLSerializer serializer = new XMLSerializer(System.out, format); 

//save xml in string var 
OutputStream outputStream = new ByteArrayOutputStream(); 
XMLSerializer serializer = new XMLSerializer(outputStream, format); 

//process
serializer.serialize(parser.getDocument()); 


String xmlText = outputStream.toString();  

System.out.println(xmlText); 

//to generate a file output use fileoutputstream instead of system.out 
//XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File("book.xml")), format);  

Url: http://totheriver.com/learn/xml/xmltutorial.html#6.2

See e) Serialize DOM to FileOutputStream to generate the xml file "book.xml" .