{"id":329557,"date":"2024-05-27T07:58:31","date_gmt":"2024-05-27T07:58:31","guid":{"rendered":"https:\/\/www.baeldung.com\/java-convert-org-w3c-dom-document-to-string"},"modified":"2024-05-27T07:58:31","modified_gmt":"2024-05-27T07:58:31","slug":"how-to-convert-org-w3c-dom-document-to-string-in-java","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2024\/05\/27\/how-to-convert-org-w3c-dom-document-to-string-in-java\/","title":{"rendered":"How to Convert org.w3c.dom.Document to String in Java"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<p><img src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"start here featured\" style=\"float: left; margin-right: 5px;\" decoding=\"async\" srcset=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured-1024x536.png 1024w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured-300x157.png 300w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured-768x402.png 768w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured-100x52.png 100w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured.png 1200w\" sizes=\"(max-width: 580px) 100vw, 580px\" \/><\/p>\n<h2 id=\"bd-overview\" data-id=\"overview\"><strong>1. Overview<\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"overview\"><\/div>\n<p>When handling XML in Java, we\u2019ll often have an instance of a <em><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.xml\/org\/w3c\/dom\/Document.html\">org.w3c.dom.Document<\/a>\u00a0<\/em>that we need to convert to a <em>String<\/em>. <strong>Typically we might want to do this for a number of reasons, such as serialization, logging, and working with HTTP requests or responses.<\/strong><\/p>\n<p>In this quick tutorial, we\u2019ll see how to convert a <em>Document<\/em> to a <em>String<\/em>. To learn more about working with XML in Java, check out our comprehensive <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/category\/xml\">series on XML<\/a>.<\/p>\n<h2 id=\"bd-creating-a-simple-document\" data-id=\"creating-a-simple-document\"><strong>2. Creating a Simple Document<\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"creating-a-simple-document\"><\/div>\n<p>Throughout this tutorial, the focus of our examples will be a simple XML document describing some fruit:<\/p>\n<pre><code class=\"language-xml\">&lt;fruit&gt;\r\n    &lt;name&gt;Apple&lt;\/name&gt;\r\n    &lt;color&gt;Red&lt;\/color&gt;\r\n    &lt;weight unit=&quot;grams&quot;&gt;150&lt;\/weight&gt;\r\n    &lt;sweetness&gt;7&lt;\/sweetness&gt;\r\n&lt;\/fruit&gt;<\/code><\/pre>\n<p>Let&#8217;s go ahead and create an XML <em>Document<\/em> object from that string:<\/p>\n<pre><code class=\"language-java\">private static final String FRUIT_XML = &quot;&lt;fruit&gt;&lt;name&gt;Apple&lt;\/name&gt;&lt;color&gt;Red&lt;\/color&gt;&lt;weight unit=\\&quot;grams\\&quot;&gt;150&lt;\/weight&gt;&lt;sweetness&gt;7&lt;\/sweetness&gt;&lt;\/fruit&gt;&quot;; \r\npublic static Document getDocument() throws SAXException, IOException, ParserConfigurationException {\r\n    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n    Document document = factory.newDocumentBuilder()\r\n      .parse(new InputSource(new StringReader(FRUIT_XML)));\r\n    return document;\r\n}<\/code><\/pre>\n<p>As we can see we create a factory for building a new <em>Document,<\/em> and then we call the <em>parse<\/em> method with the content of the given input source. In this case, our input source is a <em>StringReader<\/em> object containing our Fruit XML string payload.<\/p>\n<h2 id=\"bd-conversion-using-xml-transformation-apis\" data-id=\"conversion-using-xml-transformation-apis\"><strong>3. Conversion Using XML Transformation APIs<\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"conversion-using-xml-transformation-apis\"><\/div>\n<p><strong>The <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.xml\/javax\/xml\/transform\/package-summary.html\"><em>javax.xml.transform<\/em><\/a> package contains a set of generic APIs for performing transformations from a source to a result<\/strong>. In our case, the source is the XML document and the result is the output string:<\/p>\n<pre><code class=\"language-java\">public static String toString(Document document) throws TransformerException {\r\n    TransformerFactory transformerFactory = TransformerFactory.newInstance();\r\n    Transformer transformer = transformerFactory.newTransformer();\r\n    StringWriter stringWriter = new StringWriter();\r\n    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));\r\n    return stringWriter.toString();\r\n}<\/code><\/pre>\n<p>Let\u2019s walk through the key parts of our <em>toString<\/em> method:<\/p>\n<p>First, we start by creating our <em>TransformerFactory<\/em>. We\u2019ll use this factory to create the transformer,<b>\u00a0<\/b>and in this example, the transformer will simply use the platform&#8217;s default.<\/p>\n<p>Now, we can specify the source and result of the transformation. Here, we\u2019ll use our <em>Document<\/em> to construct a DOM source and a <em>StringWriter<\/em> to hold the result.<\/p>\n<p><strong>Finally, we call <em>toString\u00a0<\/em>on our <em>StringWriter<\/em> object, which returns the character stream&#8217;s current value as a string.<\/strong><\/p>\n<h2 id=\"bd-unit-testing\" data-id=\"unit-testing\">4. Unit Testing<\/h2>\n<div class=\"bd-anchor\" id=\"unit-testing\"><\/div>\n<p>Now we have a simple way to convert XML documents to strings, let&#8217;s go ahead and test it works properly:<\/p>\n<pre><code class=\"language-java\">@Test\r\npublic void givenXMLDocument_thenConvertToStringSuccessfully() throws Exception {\r\n    Document document = XmlDocumentToString.getDocument();\r\n    String expectedDeclartion = &quot;&lt;?xml version=\\&quot;1.0\\&quot; encoding=\\&quot;UTF-8\\&quot; standalone=\\&quot;no\\&quot;?&gt;&quot;;\r\n    assertEquals(expectedDeclartion + XmlDocumentToString.FRUIT_XML, XmlDocumentToString.toString(document));\r\n}<\/code><\/pre>\n<p><strong>Note that our conversion adds the standard XML declaration to the start of the string by default. In our test, we simply check that the converted string matches the original fruit XML,<\/strong>\u00a0including the standard declaration.<\/p>\n<h2 id=\"bd-customizing-the-output\" data-id=\"customizing-the-output\"><strong>5. Customizing the Output<\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"customizing-the-output\"><\/div>\n<p>Now, let&#8217;s take a look at our output. By default, our transformer doesn&#8217;t apply any kind of output formatting:<\/p>\n<pre><code class=\"language-bash\">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;&lt;fruit&gt;&lt;name&gt;Apple&lt;\/name&gt;&lt;color&gt;Red&lt;\/color&gt;&lt;weight unit=&quot;grams&quot;&gt;150&lt;\/weight&gt;&lt;sweetness&gt;7&lt;\/sweetness&gt;&lt;\/fruit&gt;<\/code><\/pre>\n<p>Obviously, it doesn&#8217;t take long for our XML documents to become difficult to read using this one-line formatting, especially for large documents. Fortunately, the <em>Transformer<\/em> interface provides a variety of output properties to help us<em>.\u00a0<\/em><\/p>\n<p>Let\u2019s refactor our transformation code a little bit using some of these output properties:<\/p>\n<pre><code class=\"language-java\">public static String toStringWithOptions(Document document) throws TransformerException {\r\n    Transformer transformer = getTransformer();\r\n    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, &quot;yes&quot;);\r\n    transformer.setOutputProperty(OutputKeys.INDENT, &quot;yes&quot;);\r\n    transformer.setOutputProperty(&quot;{http:\/\/xml.apache.org\/xslt}indent-amount&quot;, &quot;4&quot;);\r\n    StringWriter stringWriter = new StringWriter();\r\n    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));\r\n    return stringWriter.toString();\r\n}\r\nprivate static Transformer getTransformer() throws TransformerConfigurationException {\r\n    TransformerFactory transformerFactory = TransformerFactory.newInstance();\r\n    return transformerFactory.newTransformer();\r\n}<\/code><\/pre>\n<p>Sometimes, we might want to exclude the XML declaration. We can configure our transformer to do this by setting the <em>OutputKeys.OMIT_XML_DECLARATION<\/em> property.<\/p>\n<p>Now, to apply some indentation, we can use two properties: <em>OutputKeys.INDENT<\/em> and the indent-amount property to specify the amount of indentation. This will indent the output correctly, as by default,\u00a0the indentation uses zero spaces.<\/p>\n<p>With the above properties set, we get a much nicer-looking output:<\/p>\n<pre><code class=\"language-xml\">&lt;fruit&gt;\r\n    &lt;name&gt;Apple&lt;\/name&gt;\r\n    &lt;color&gt;Red&lt;\/color&gt;\r\n    &lt;weight unit=&quot;grams&quot;&gt;150&lt;\/weight&gt;\r\n    &lt;sweetness&gt;7&lt;\/sweetness&gt;\r\n&lt;\/fruit&gt;<\/code><\/pre>\n<h2 id=\"bd-conclusion\" data-id=\"conclusion\"><strong>6. Conclusion<\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>In this short article, we learned how to create an XML Document from a Java <em>String<\/em> object, and then we saw how to convert this Document back into a <em>String<\/em> using the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/docs.oracle.com\/en\/java\/javase\/21\/docs\/api\/java.xml\/javax\/xml\/transform\/package-summary.html\"><em>javax.xml.transform<\/em><\/a> package.<\/p>\n<p>In addition to this, we also saw several ways we can customize the output of the XML, which can be useful when logging the XML to the console.<\/p>\n<p>As always, the full source code of the article is available\u00a0<a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/xml-2\">over on GitHub<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/897762899\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/897762899\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-7-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Post to X.com\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/x.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-convert-org-w3c-dom-document-string#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-convert-org-w3c-dom-document-string\/feed\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p><img decoding=\"async\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"start here featured\"><\/p>\n<p>Learn how to create an XML Document from a Java String object and convert it back into a String using the javax.xml.transform package.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>\u00a0<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/897762899\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-7-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>\u00a0<a title=\"Post to X.com\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/x.png\"><\/a>\u00a0<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>\u00a0<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/897762899\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>\u00a0<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-convert-org-w3c-dom-document-string#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>\u00a0<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-convert-org-w3c-dom-document-string\/feed\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>\u00a0<\/div>\n<\/div>","protected":false},"author":881,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"How to Convert org.w3c.dom.Document to String in Java - ITTeacherITFreelance.hk","description":"Learn how to create an XML Document from a Java String object and convert it back into a String using the javax.xml.transform package. \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0"},"footnotes":""},"categories":[6,1307],"tags":[10800],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329557"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/881"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=329557"}],"version-history":[{"count":1,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329557\/revisions"}],"predecessor-version":[{"id":329558,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329557\/revisions\/329558"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=329557"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=329557"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=329557"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}