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!
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.
org.w3c.dom. Provides the interfaces for the Document Object Model (DOM).
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();
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With