HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java XML / Java String to XML – Parse String to XML DOM Example

Java String to XML – Parse String to XML DOM Example

In Java, XML is represented with org.w3c.dom.Document object. In this XML tutorial, we will learn to –

  1. Convert XML string to XML Document
  2. Convert XML file content to XML Document

1) Convert String to XML Document

To convert XML string to XML Dom, we need following classes:

  • javax.xml.parsers.DocumentBuilder : Defines the API to obtain XML DOM Document instances from an XML content from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.
  • javax.xml.parsers.DocumentBuilderFactory : Defines a factory API that enables applications to obtain a parser (DocumentBuilder) that produces DOM object trees from XML content.
  • org.w3c.dom.Document : It represents the entire XML DOM. Conceptually, it is the root of the document tree, and provides the access to the document’s data further down into the tree, through factory methods.
  • java.io.StringReader : Create a stream from String content. DocumentBuilder uses this stream to read XML content for parsing.
package com.howtodoinjava.demo;

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class StringtoXMLExample 
{
	public static void main(String[] args) 
	{
		final String xmlStr = "<employees>" + 
								"	<employee id=\"101\">" + 
								"		 <name>Lokesh Gupta</name>" + 
								"	    <title>Author</title>" + 
								"	</employee>" + 
								"	<employee id=\"102\">" + 
								"		 <name>Brian Lara</name>" + 
								"	    <title>Cricketer</title>" + 
								"	</employee>" + 
								"</employees>";
		
		//Use method to convert XML string content to XML Document object
		Document doc = convertStringToXMLDocument( xmlStr );
		
		//Verify XML document is build correctly
		System.out.println(doc.getFirstChild().getNodeName());
	}

	private static Document convertStringToXMLDocument(String xmlString) 
	{
		//Parser that produces DOM object trees from XML content
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		//API to obtain DOM Document instance
		DocumentBuilder builder = null;
		try 
		{
			//Create DocumentBuilder with default configuration
			builder = factory.newDocumentBuilder();
			
			//Parse the content to Document object
			Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
			return doc;
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}
}

//Output:

employees

2) Convert XML file to XML Document

To get the XML dom from XML file, instead of passing XML string to DocumentBuilder, pass the file path to let parser read the file content directly.

We have employees.xml file which has XML content, we will read to get XML document.

<employees>
	<employee id="101">
		 <name>Lokesh Gupta</name>
	    <title>Author</title>
	</employee>
	<employee id="102">
		 <name>Brian Lara</name>
	    <title>Cricketer</title>
	</employee>
</employees>
package com.howtodoinjava.demo;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class StringtoXMLExample 
{
	public static void main(String[] args) 
	{
		final String xmlFilePath = "employees.xml";
		
		//Use method to convert XML string content to XML Document object
		Document doc = convertXMLFileToXMLDocument( xmlFilePath );
		
		//Verify XML document is build correctly
		System.out.println(doc.getFirstChild().getNodeName());
	}

	private static Document convertXMLFileToXMLDocument(String filePath) 
	{
		//Parser that produces DOM object trees from XML content
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		//API to obtain DOM Document instance
		DocumentBuilder builder = null;
		try 
		{
			//Create DocumentBuilder with default configuration
			builder = factory.newDocumentBuilder();
			
			//Parse the content to Document object
			Document doc = builder.parse(new File(filePath));
			return doc;
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}
}

//Output:

employees

Drop me your questions in comments section.

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. tarun Anantala

    November 27, 2019

    how to write xpath expression for xml which has name space for this document builder

Comments are closed on this article!

Search Tutorials

Java XML Tutorial

  • Java – Read XML DOM Parser
  • Java – Read XML SAX Parser
  • Java – Read XML JDOM2 Parser
  • Java – Read XML StAX Parser
  • Java – DOM vs SAX Parser
  • Java – Convert XML to Properties
  • Java – Convert Properties to XML
  • Java – Convert String to XML
  • Java – Convert XML to String
  • Java – XPath Tutorial
  • Java – Evaluate XPath on DOM
  • Java – Evaluate XPath on String
  • Java – XPath Examples
  • Java – XPath NamespaceContext
  • Java – Get Attribute using XPath
  • Java – XPath Attribute Examples
  • Java – Check if XML tag exists?

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)