{"id":37288,"date":"2023-10-31T20:45:57","date_gmt":"2023-10-31T20:45:57","guid":{"rendered":"https:\/\/www.baeldung.com\/java-convert-string-with-xml-to-dom"},"modified":"2023-10-31T20:45:57","modified_gmt":"2023-10-31T20:45:57","slug":"convert-string-containing-xml-to-org-w3c-dom-document","status":"publish","type":"post","link":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/2023\/10\/31\/convert-string-containing-xml-to-org-w3c-dom-document\/","title":{"rendered":"Convert String Containing XML to org.w3c.dom.Document"},"content":{"rendered":"<p><img src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-7-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" decoding=\"async\" style=\"float: left; margin-right: 5px;\" loading=\"lazy\" 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-introduction\" data-id=\"introduction\">1. Introduction<\/h2>\n<div class=\"bd-anchor\" id=\"introduction\"><\/div>\n<p>One of the most common data formats today is <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/extensible-markup-language\">XML<\/a> (Extensible Markup Language), which is widely used in structuring and exchanging data between applications.<\/p>\n<p>Moreover, this use case is common in Java, where we must change some pieces of XML markup text to <em>org.w3c.dom.Document<\/em> object.<\/p>\n<p><strong>In this tutorial, we\u2019ll discuss converting a string with XML-based content into <em>Org.w3c.dom.Document<\/em> in Java.<\/strong><\/p>\n<h2 id=\"bd-orgw3cdomdocument\" data-id=\"orgw3cdomdocument\">2. <em>org.w3c.dom.Document<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"orgw3cdomdocument\"><\/div>\n<p>The <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-write-xml-document-file\"><em>org.w3c.dom.Document<\/em><\/a> is an integral component of the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-xerces-dom-parsing\">Document Object Model (DOM)<\/a> XML API in Java. This essential class represents an entire XML document and provides a comprehensive set of methods for navigating, modifying, and retrieving data from XML documents. When working with XML in Java, <em>the org.w3c.dom.Document<\/em> object becomes an indispensable tool.<\/p>\n<p>To better understand how to create an <em>org.w3c.dom.Document<\/em> object, let&#8217;s look at the following example:<\/p>\n<pre><code class=\"language-java\">try {\r\n    \/\/ Create a DocumentBuilderFactory\r\n    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n    \/\/ Create a DocumentBuilder\r\n    DocumentBuilder builder = factory.newDocumentBuilder();\r\n    \/\/ Create a new Document\r\n    Document document = builder.newDocument();\r\n    \/\/ Create an example XML structure\r\n    Element rootElement = document.createElement(&quot;root&quot;);\r\n    document.appendChild(rootElement);\r\n    Element element = document.createElement(&quot;element&quot;);\r\n    element.appendChild(document.createTextNode(&quot;XML Document Example&quot;));\r\n    rootElement.appendChild(element);\r\n    \r\n} catch (ParserConfigurationException e) {\r\n    e.printStackTrace();\r\n}<\/code><\/pre>\n<p>In the previous code, we start by creating the necessary elements for the parsing of XML, such as <em>DocumentBuilderFactory<\/em> and <em>DocumentBuilder<\/em>. After that, it builds a basic XML schema with an initial node element labeled <em>&#8220;root&#8221;<\/em> encompassing another child node element referred to as <em>&#8220;element&#8221;<\/em> that has the string <em>&#8220;XML document example&#8221;<\/em>. Moreover, the XML output should be as follows:<\/p>\n<pre><code class=\"language-xml\">&lt;root&gt;\r\n    &lt;element&gt;XML Document Example&lt;\/element&gt;\r\n&lt;\/root&gt;<\/code><\/pre>\n<h2 id=\"bd-parsing-xml-from-a-string\" data-id=\"parsing-xml-from-a-string\">3. Parsing XML from a String<\/h2>\n<div class=\"bd-anchor\" id=\"parsing-xml-from-a-string\"><\/div>\n<p>Parsing of the XML string is needed for converting the string containing XML into an <em>org.w3c.dom.Document<\/em>. Fortunately, there are several XML parsing libraries in Java, which include <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-xml-libraries\">DOM<\/a>, <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-sax-parser\">SAX<\/a>, and <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-stax\">StAX<\/a>.<\/p>\n<p>This article takes it easy by concentrating on the DOM parser for a simple explanation. Let&#8217;s walk through a step-by-step example of how to parse a string with XML and create an <em>org.w3c.dom.Document<\/em> object:<\/p>\n<pre><code class=\"language-java\">@Test\r\npublic void givenValidXMLString_whenParsing_thenDocumentIsCorrect()\r\n  throws ParserConfigurationException {\r\n    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n    DocumentBuilder builder = factory.newDocumentBuilder();\r\n    String xmlString = &quot;&lt;root&gt;&lt;element&gt;XML Parsing Example&lt;\/element&gt;&lt;\/root&gt;&quot;;\r\n    InputSource is = new InputSource(new StringReader(xmlString));\r\n    Document xmlDoc = null;\r\n    try {\r\n        xmlDoc = builder.parse(is);\r\n    } catch (SAXException e) {\r\n        throw new RuntimeException(e);\r\n    } catch (IOException e) {\r\n        throw new RuntimeException(e);\r\n    }\r\n    assertEquals(&quot;root&quot;, xmlDoc.getDocumentElement().getNodeName());\r\n    assertEquals(&quot;element&quot;, xmlDoc.getDocumentElement().getElementsByTagName(&quot;element&quot;).item(0).getNodeName());\r\n    assertEquals(&quot;XML Parsing Example&quot;,\r\n      xmlDoc.getDocumentElement().getElementsByTagName(&quot;element&quot;).item(0).getTextContent());\r\n}<\/code><\/pre>\n<p>In the above code, we create a <em>DocumentBuilderFactory<\/em> and <em>DocumentBuilder<\/em> that are critical for XML parsing. <strong>Additionally, we define a sample XML string (<em>xmlString<\/em>) that is converted into an <em>InputSource<\/em> for parsing. We parse XML within a <em>try-catch<\/em> block and <em>catch<\/em> any possible exception like <em>SAXException<\/em> or <em>IOException<\/em>.<\/strong><\/p>\n<p>Finally, we employ a series of assertions to verify the correctness of the parsed XML document, including checks for the root element&#8217;s name using <em>getDocumentElement().getNodeName()<\/em>, the child element&#8217;s name using <em>getDocumentElement().getElementsByTagName()<\/em>, and the text content within the child element.<\/p>\n<h2 id=\"bd-conclusion\" data-id=\"conclusion\">4. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>In conclusion, for any competent Java developer who deals with XML-based data in numerous applications, from data processing to web services or configurational tasks, it is vital to know how to <em>operate org.w3c.dom.Document<\/em> (NS).<\/p>\n<p>As always, the complete code samples for this article can be found\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\/804700271\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/804700271\/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\/804700271\/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=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/804700271\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/804700271\/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\/804700271\/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-string-xml-dom#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-string-xml-dom\/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","protected":false},"excerpt":{"rendered":"<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=\"\" loading=\"lazy\"><\/p>\n<p>Learn how to convert a string with XML-based content into Org.w3c.dom.Document in Java.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/804700271\/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\/804700271\/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=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/804700271\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\"><\/a>\u00a0<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/804700271\/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\/804700271\/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-string-xml-dom#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-string-xml-dom\/feed\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>\u00a0<\/div>\n","protected":false},"author":259,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"site-container-style":"default","site-container-layout":"default","site-sidebar-layout":"default","disable-article-header":"default","disable-site-header":"default","disable-site-footer":"default","disable-content-area-spacing":"default","footnotes":""},"categories":[22],"tags":[61,122,127,129,124,128,125,132,131,133,126,130,123,66,94,88,97,56,64,65,60,112,40,75,95,104,33,120,105,101,98,115,30,29,41,86,70,69,68,72,71,26,118,108,87,46,55,48,52,54,51,50,83,62,58,57,109,35,59,63,85,79,82,96,80,27,81,114,44,42,43,45,38,39,110,117,100,111,116,73,89,90,92,91,93,84,78,37,102,34,36,77,67,74,99,113,119,28,121,32,47,49,53,103,31,76,12678],"class_list":["post-37288","post","type-post","status-publish","format-standard","hentry","category-mobile","tag-airpods","tag-anime","tag-anime-characters","tag-anime-cosplay","tag-anime-edits","tag-anime-merchandise","tag-anime-movies","tag-anime-news","tag-anime-recommendations","tag-anime-reviews","tag-anime-series","tag-anime-streaming","tag-animes","tag-app-store","tag-app-store-samsung","tag-appgallery","tag-appgallery-oneplus","tag-apple","tag-apple-music","tag-apple-tv","tag-apple-watch","tag-bbc-sport","tag-best-mobile-games","tag-bixby","tag-bixby-xiaomi","tag-champions-league","tag-cyberpunk","tag-cyberpunk-2077","tag-fantasy-football","tag-fifa","tag-football","tag-formula-1","tag-fortnite","tag-free-fire","tag-free-mobile-games","tag-freebuds-pro","tag-galaxy-a52","tag-galaxy-note-20","tag-galaxy-s21","tag-galaxy-watch-4","tag-galaxy-z-fold-3","tag-game","tag-games","tag-golf","tag-harmonyos","tag-how-to-backup-iphone","tag-how-to-factory-reset-iphone","tag-how-to-reset-iphone","tag-how-to-restore-iphone","tag-how-to-unlock-iphone","tag-how-to-unlock-iphone-5","tag-how-to-unlock-iphone-6","tag-huawei","tag-ios","tag-ipad","tag-iphone","tag-live-soccer","tag-lol","tag-macbook","tag-macos","tag-mate-40-pro","tag-mi-11-lite","tag-mi-home-security-camera-basic-1080p","tag-mi-home-security-camera-basic-1080p-huawei","tag-mi-smart-band-6","tag-minecraft","tag-miui","tag-mlb-scores","tag-mobile-game-design","tag-mobile-game-development","tag-mobile-game-marketing","tag-mobile-game-monetization","tag-mobile-games","tag-mobile-gaming","tag-nba-scores","tag-nba-standings","tag-nfl","tag-nfl-scores","tag-nhl-scores","tag-one-ui","tag-oneplus","tag-oneplus-9-pro","tag-oneplus-buds-pro","tag-oneplus-nord-ce-5g","tag-oxygenos","tag-p40-pro-plus","tag-poco-x3-pro","tag-pokemon","tag-premier-league","tag-pubg","tag-pubg-mobile","tag-redmi-note-10-pro","tag-samsung","tag-samsung-pay","tag-soccer","tag-sports","tag-steam","tag-steeam","tag-top-10-anime","tag-valorant","tag-when-do-the-iphone-7-come-out","tag-when-does-the-iphone-7-come-out","tag-when-is-the-iphone-7-coming-out","tag-world-cup","tag-xbox-series-x","tag-xiaomi","tag-xml"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts\/37288","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/users\/259"}],"replies":[{"embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/comments?post=37288"}],"version-history":[{"count":1,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts\/37288\/revisions"}],"predecessor-version":[{"id":37389,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/posts\/37288\/revisions\/37389"}],"wp:attachment":[{"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/media?parent=37288"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/categories?post=37288"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gamefootballmobileanimeiphone.com\/index.php\/wp-json\/wp\/v2\/tags?post=37288"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}