Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an org.w3c.dom.Node into a String

Sorry I'm a Java/XML newbie - and can't seem to figure this one out. It seems it's possible to convert a Document object to a string. However, I want to convert a Node object into a string. I am using org.ccil.cowan.tagsoup Parser for my purpose.

I'm retrieving the Node by something like...

 parser = new org.ccil.cowan.tagsoup.Parser()    parser.setFeature(namespaceaware, false)   Transformer transformer = TransformerFactory.newInstance().newTransformer();   DOMResult domResult = new DOMResult();    transformer.transform(new SAXSource(parser, new InputSource(in)), domResult);  Node n = domResult.getNode();         // I'm interested in the first child, so...  Node myNode = n.getChildNodes().item(0);   // convert myNode to string..  // what to do here? 

The answer may be obvious, but I can't seem to figure out from the core Java libraries how to achieve this. Any help is much appreciated!

like image 299
ragebiswas Avatar asked Feb 08 '10 16:02

ragebiswas


People also ask

How do I convert a file to string in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion. String convertDocumentToString(Document doc) : This method will take input as Document and convert it to String.

What is org w3c DOM node?

org.w3c.dom. Provides the interfaces for the Document Object Model (DOM).

How do I convert an element to a document?

Element element = //code to get a element Node node = //code to get a node //document from Node Document document = node. getOwnerDocument(); //document from a Element Document document = element. getOwnerDocument();


1 Answers

You can use a Transformer (error handling and optional factory configuration omitted for clarity):

Node node = ...; StringWriter writer = new StringWriter(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new DOMSource(node), new StreamResult(writer)); String xml = writer.toString(); // Use xml ... 
like image 144
Kevin Avatar answered Oct 07 '22 19:10

Kevin