Je souhaite convertir un objet org.w3c.dom.Document en chaîne. J'utilise Java 6 et suis ouvert à toute technologie (totalement gratuite) à la hauteur de la tâche. J'ai essayé la solution à partir de ce fil de discussion - Existe-t-il une autre solution? manière élégante de convertir un document XML en chaîne dans Java que ce code? , où ils ont
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
String html = lsSerializer.writeToString(doc);
mais a été accueilli avec l'exception horrible suivante…
org.w3c.dom.DOMException: DOM method not supported
at org.w3c.tidy.DOMDocumentImpl.getImplementation(DOMDocumentImpl.Java:129)
at com.myco.myproj.cleaners.JTidyCleaner.outputDocAsString(JTidyCleaner.Java:74)
at com.myco.myproj.cleaners.JTidyCleaner.parse(JTidyCleaner.Java:63)
at com.myco.myproj.util.NetUtilities.getUrlAsDocument(NetUtilities.Java:51)
at com.myco.myproj.parsers.AbstractHTMLParser.getEventFromElement(AbstractHTMLParser.Java:131)
at com.myco.myproj.parsers.AbstractHTMLParser.parsePage(AbstractHTMLParser.Java:100)
at com.myco.myproj.parsers.AbstractHTMLParser.getEvents(AbstractHTMLParser.Java:63)
at com.myco.myproj.domain.EventFeed.refresh(EventFeed.Java:87)
at com.myco.myproj.domain.EventFeed.getEvents(EventFeed.Java:72)
at com.myco.myproj.parsers.impl.ChicagoCouncilGlobalAffairsParserTest.testParser(ChicagoCouncilGlobalAffairsParserTest.Java:21)
at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:39)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:25)
at Java.lang.reflect.Method.invoke(Method.Java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.Java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.Java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.Java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.Java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.Java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.Java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.Java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.Java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.Java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.Java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.Java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.Java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.Java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.Java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.Java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.Java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.Java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.Java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.Java:174)
at org.Eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.Java:50)
at org.Eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.Java:38)
at org.Eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.Java:467)
at org.Eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.Java:683)
at org.Eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.Java:390)
at org.Eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.Java:197)
Si vous êtes d'accord pour effectuer la transformation, vous pouvez essayer ceci.
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
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);
System.out.println("XML IN String format is: \n" + writer.toString());
utiliser quelque chose comme
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;
}
}
Cela a fonctionné pour moi, comme documenté sur cette page :
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();
Une version de Scala basée sur la réponse de Zaz).
case class DocumentEx(document: Document) {
def toXmlString(pretty: Boolean = false):Try[String] = {
getStringFromDocument(document, pretty)
}
}
implicit def documentToDocumentEx(document: Document):DocumentEx = {
DocumentEx(document)
}
def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
try
{
val domSource= new DOMSource(doc)
val writer = new StringWriter()
val result = new StreamResult(writer)
val tf = TransformerFactory.newInstance()
val transformer = tf.newTransformer()
if (pretty)
transformer.setOutputProperty(OutputKeys.INDENT, "yes")
transformer.transform(domSource, result)
Success(writer.toString);
}
catch {
case ex: TransformerException =>
Failure(ex)
}
}
Avec cela, vous pouvez faire soit doc.toXmlString()
ou appeler la fonction getStringFromDocument(doc)
.