Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert DOM to String in android?

Tags:

android

How To convert Document response in to String?

I tried this code but it doesn't work:

Element root = response.getDocumentElement();
String s = root.toString();
like image 355
Sunil_Suthar Avatar asked Feb 29 '12 09:02

Sunil_Suthar


2 Answers

Try this:

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
{
    try
    {
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    }
    catch(TransformerException ex)
    {
       ex.printStackTrace();
       return null;
    }
}
like image 140
Caner Avatar answered Nov 17 '22 09:11

Caner


Somthing like that:

    public static String xmlToString(Node node) {
        try {
            Source source = new DOMSource(node);
            StringWriter stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);
            TransformerFactory factory = TransformerFactory.newInstance();
            //factory.setAttribute("indent-number", "4");
            Transformer transformer = factory.newTransformer();
            transformer.transform(source, result);
            return stringWriter.getBuffer().toString();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
             e.printStackTrace();
        }
        return null;
}
like image 30
Vyacheslav Shylkin Avatar answered Nov 17 '22 09:11

Vyacheslav Shylkin