Another common question is how one gets a string representation of a given DOM object.
Here's a method that returns the string representation of a given org.w3c.dom.Node object (usually an instance of org.w3c.dom.Element or org.w3c.dom.Document):
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class Util {
public static byte[] doc2bytes(Node node) {
try {
Source source = new DOMSource(node);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return out.toByteArray();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
}
(See also DocumentToString)
XmlFaq CategoryCodeSamples
|