Convert element (org.w3c.dom) to string in Java

I am having a slight problem converting an Element object to String. Because I need a string that will be passed to a specific method. I tried using .toString () or using the String variable assigning it. None of the tests were correct. As we can easily convert, the string object should also show the exact XML structure as it shows for the element.

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

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

+4
source share
2 answers
 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;

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();

try it

+5
source

API- .

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

Source: https://habr.com/ru/post/1608664/


All Articles