How do I convert a org.w3c.dom.Document object to a String?

后端 未结 4 748
我在风中等你
我在风中等你 2020-12-02 16:41

I want to convert a org.w3c.dom.Document object to a String. I\'m using Java 6 and am open to using any (completely free) technology that is up to the task. I tried the so

4条回答
  •  春和景丽
    2020-12-02 17:00

    A Scala version based on Zaz's answer.

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

    With that, you can do either doc.toXmlString() or call the getStringFromDocument(doc) function.

提交回复
热议问题