How to convert Array to XML in Java – 2 easy way

In this post, we will see how to convert Array to XML in Java. We can convert Array to XML format, XML document, and as well as XML String.

The Array is also one of the most important topics of the Java programming language. So in some scenarios, we may need to convert Array to other formats. Similarly, we can also convert Array to XML in Java.

How to convert Array to XML in Java?

We can convert the Array to XML in Java by using just a for loop. We have used this approach to convert the String Array to XML format which will represent a String value.

If you want to see the complete program to convert String Array to XML document, then you refer the program just next to this program.

Let’s see the program now to convert String Array to XML format.

/**
 * How to convert String array to xml format in Java?
 */
package cf.java.array;

public class ArrayToXMLFormat {

	// main( ) method
	public static void main(String[] args) {
		// Declare a two dimensional String Array
		String[][] data = { { "name", "Codingface" }, { "type", "website" }, { "address", "https://codingface.com" } };
		// Display Array in XML format
		System.out.println("<?xml version=\"1.0\"?>");
		System.out.println("<data>");
		for (int i = 0; i < data.length; i++) {
			System.out.println("   <" + data[i][0] + "> " + data[i][1] + " </" + data[i][0] + ">");
		}
		System.out.println("</data>");
	}

}Code language: PHP (php)

Output:

<?xml version="1.0"?>
<data>
   <name> Codingface </name>
   <type> website </type>
   <address> https://codingface.com </address>
</data>
Code language: HTML, XML (xml)

Explanation:

In this program, we have taken a String Array as a user given 2 Dimensional String Array and then by using a simple for loop, we have displayed the given String Array in XML format.

If you want to format the given String Array and convert them to XML, you can refer to the below program here.

Let’s see the below program to convert String Array to XML in Java now.

Also Read: Java Program To Remove Duplicate Words In A String – 3 Ways

Java program to convert String Array to XML document:

/**
 * How to convert String array to xml document in Java?
 */
package cf.java.array;

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 ArrayToXML {

	// main( ) method
	public static void main(String[] args) {
		String xmlData = "";
		// Declare a two dimensional String Array
		String[][] data = { { "name", "Codingface" }, { "type", "website" }, { "address", "https://codingface.com" } };

		xmlData = xmlData + "<?xml version=\"1.0\"?>\n" + "<data>\n";
		for (int i = 0; i < data.length; i++) {
			xmlData = xmlData + "   <" + data[i][0] + "> " + data[i][1] + " </" + data[i][0] + ">\n";
		}
		xmlData = xmlData + "</data>";
		
		// Produce DOM object trees from XML String
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		// Create DOM DocumentBuilder instance
	    DocumentBuilder docBuilder;
		try {
			// Create DocumentBuilder 
			docBuilder = docBuilderFactory.newDocumentBuilder();
			// Convert DocumentBuilder Document obj
			Document doc = docBuilder.parse(new InputSource(new StringReader(xmlData)));
			// Display success message
			System.out.println("XML document formed successfully");
			
			/**
			 * We have converted the given String data into XML Document.
			 * You can also convert this XML doc to XML string again
			 */
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Code language: JavaScript (javascript)

Explanation of above program:

In the above program, we have first converted the given String Array to XML String “xmlData.

We have converted this String Array into an XML document by using 3 classes DocumentBuilderFactory, DocumentBuilder, and Document.

javax.xml.parsers.DocumentBuilderFactory class:

Represents a factory API that allows our applications to get a parser that generates DOM object trees of XML documents.

javax.xml.parsers.DocumentBuilder class:

Represents the API to retrieve DOM Document instances of an XML document. Any application or programmer can retrieve the  Document of XML through this class.

org.w3c.dom.Document class:

The Document interface describes the complete HTML or XML document. Basically, it is the source of the document tree and gives initial access to the document’s data.

Also Read: How To Check String Contains Special Characters In Java

You can also convert the XML document into XML String by using the below piece of code after getting the XML document in the above program inside try block after line no. 36.

TransformerFactory tfFac = TransformerFactory.newInstance();
Transformer tf = tfFac.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter sWriter = new StringWriter();
StreamResult res = new StreamResult(sWriter);
tf.transform(source, res);
String str= sWriter.getBuffer().toString();
System.out.println(“Result of xml to string conversion: ” + str);Code language: JavaScript (javascript)

People also ask for:

  • How to convert array to XML in java?
  • How to convert String Array to XML Java?
  • How to convert String Array to XML document?
  • How to convert XML document to XML String?

Leave a Comment