Syed
Syed

Reputation: 2607

Convert Element(org.w3c.dom) to String in Java

I'm having a small issue of converting Element object to String. Because I need a string to be passed to a particular method. I've tried by using .toString() or using a String variable assigning to it. None of the trials were correct. How can we easily convert and the string object also should show the exact XML structure as it is showing for Element.

Element element = (Element) xmlList.item(i);

The above "element" object shows in XML format. I want to convert the same in String in XML format

Upvotes: 10

Views: 18354

Answers (2)

virendrao
virendrao

Reputation: 1813

Try this

needed packages:

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.StringWriter;

code:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(<your-element-obj>);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);

String strObject = result.getWriter().toString();

Upvotes: 15

emilianogc
emilianogc

Reputation: 930

You need to use the transformer API.

TransformerFactory.newInstance().newTransformer().transform(new DOMSource(element), new StreamResult(System.out));

Upvotes: 6

Related Questions