web-dev-qa-db-ja.com

org.w3c.dom.Documentオブジェクトを文字列に変換するにはどうすればよいですか?

Org.w3c.dom.Documentオブジェクトを文字列に変換したい。私はJava 6を使用していますが、タスクに応じた(完全に無料の)テクノロジーを使用することもできます。このスレッドから解決策を試しました- このコードよりもJavaでXMLドキュメントを文字列に変換するよりエレガントな方法はありますか?

DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
String html = lsSerializer.writeToString(doc);  

しかし、次の恐ろしい例外で迎えられました...

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)
76
Dave

変換を実行しても問題ない場合は、これを試してください。

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

のようなものを使う

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;
    }
} 
82
Zaz Gmy

このページ で文書化されているように、これは私にとってはうまくいきました。

TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();
5
Sonam Shinare

Zazの回答に基づくScalaバージョン。

  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)
    }
  }

これにより、doc.toXmlString()を実行するか、getStringFromDocument(doc)関数を呼び出すことができます。

1
k.c. sham