Thursday, January 28, 2010

Xalan-Java Version 2.7.1 Extensions - Redirect


Xalan-Java Version 2.7.1 Extensions: Extension elements and functions provide a powerful mechanism for extending and simplifying what you can do with an XLST processor like Xalan. With input and contributions from the XML open-source developer community, we are working on placing the most useful extensions in an extensions library distributed with Xalan-Java.

Redirect Extension:A standard XSL transformation involves an XSL stylesheet, an XML source tree, and the transformation result tree. The transformation sends the entire result to a single javax.xml.transform.Result object.

The namespace for the Redirect extension is:
http://xml.apache.org/xalan/redirect

It supplies three extension elements that you can use to redirect portions of your transformation output to multiple files: <open>, <write>, and <close>. If you use the <write> element alone, the extension opens a file, writes to it, and closes the file immediately. If you want explicit control over the opening and closing of files, use <write> in conjunction with the <open> and <close> elements.

The <open> and <write> elements include a file attribute and/or a select attribute to designate the output file. The file attribute takes a string, so you can use it to directly specify the output file name. The select attribute takes an XPath expression, so you can use it to dynamically generate the output file name. If you include both attributes, the Redirect extension first evaluates the select attribute, and falls back to the file attribute if the select attribute expression does not return a valid file name.

The <open> and <write> elements also support an append attribute. If the append attribute is set to true or yes, then the result is appended to the output file.

Simple Example of using Redirect extension with XSLT:

I have a XML file which contains some set of XML elements as shown in Source.XML below. My requirement is, I want to move all <REF1> elements to file REF1.XML, all <REF2> elements to REF2.XML and so on.

A simple XSLT using Redirect extension from Xalan can do the trick as shown in MultiRedirect.XSL. I am selecting all <REF1> elements and copying it to REF1.XML using Redirect extension and Similar for all <REF2>, <REF3>, <REF4> and <REF5> elements. On XSLT transformation of Source.XML by MultiRedirect.XSL will create five new XML files like REF1.XML, REF2.XML, REF3.XML, REF4.XML and REF5.XML as shown below.

Before running this example you should have Xalan-J 2.7.1 available to program. I mean you should have Xalan-J 2.7.1 downloaded and set on CLASSPATH. Refer Bibliography for downloads and other references of Xalan-J 2.7.1

Source.XML


<?xml version="1.0" encoding="ISO-8859-1"?>
<Invoice>
<InvoiceHeader>

<!-- Gruop of Ref1 Elements to go in file REF1.XML -->
<Ref1 code="1">
<text>Reference Text 1</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 2</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 3</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 4</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 5</text>
</Ref1>

<!-- Gruop of Ref2 Elements to go in file REF2.XML -->
<Ref2 code="2">
<text>Reference Text 1</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 2</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 3</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 4</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 5</text>
</Ref2>

<!-- Gruop of Ref3 Elements to go in file REF3.XML -->
<Ref3 code="3">
<text>Reference Text 1</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 2</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 3</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 4</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 5</text>
</Ref3>

<!-- Gruop of Ref4 Elements to go in file REF4.XML -->
<Ref4 code="4">
<text>Reference Text 1</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 2</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 3</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 4</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 5</text>
</Ref4>

<!-- Gruop of Ref5 Elements to go in file REF5.XML -->
<Ref5 code="5">
<text>Reference Text 1</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 2</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 3</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 4</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 5</text>
</Ref5>

</InvoiceHeader>
</Invoice>



MultiRedirect.XSL


<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:redirect="http://xml.apache.org/xalan/redirect" extension-element-prefixes="redirect">

<xsl:variable name="REF1" select="'REF1.XML'"/>
<xsl:variable name="REF2" select="'REF2.XML'"/>
<xsl:variable name="REF3" select="'REF3.XML'"/>
<xsl:variable name="REF4" select="'REF4.XML'"/>
<xsl:variable name="REF5" select="'REF5.XML'"/>

<xsl:template match="/">

<!-- Redirecting REF1 Elementns to REF1.XML -->
<redirect:open select="$REF1"/>
<redirect:write select="$REF1">
<Invoice>
<InvoiceHeader>
<xsl:copy-of select="Invoice/InvoiceHeader/Ref1"/>
</InvoiceHeader>
</Invoice>
</redirect:write>
<redirect:close select="$REF1"/>

<!-- Redirecting REF2 Elementns to REF2.XML -->
<redirect:open select="$REF2"/>
<redirect:write select="$REF2">
<Invoice>
<InvoiceHeader>
<xsl:copy-of select="Invoice/InvoiceHeader/Ref2"/>
</InvoiceHeader>
</Invoice>
</redirect:write>
<redirect:close select="$REF2"/>

<!-- Redirecting REF3 Elementns to REF3.XML -->
<redirect:open select="$REF3"/>
<redirect:write select="$REF3">
<Invoice>
<InvoiceHeader>
<xsl:copy-of select="Invoice/InvoiceHeader/Ref3"/>
</InvoiceHeader>
</Invoice>
</redirect:write>
<redirect:close select="$REF3"/>

<!-- Redirecting REF4 Elementns to REF4.XML -->
<redirect:open select="$REF4"/>
<redirect:write select="$REF4">
<Invoice>
<InvoiceHeader>
<xsl:copy-of select="Invoice/InvoiceHeader/Ref4"/>
</InvoiceHeader>
</Invoice>
</redirect:write>
<redirect:close select="$REF4"/>

<!-- Redirecting REF5 Elementns to REF5.XML -->
<redirect:open select="$REF5"/>
<redirect:write select="$REF5">
<Invoice>
<InvoiceHeader>
<xsl:copy-of select="Invoice/InvoiceHeader/Ref5"/>
</InvoiceHeader>
</Invoice>
</redirect:write>
<redirect:close select="$REF5"/>

</xsl:template>

</xsl:stylesheet>


REF1.XML


<?xml version="1.0" encoding="UTF-8"?>
<Invoice>
<InvoiceHeader>
<Ref1 code="1">
<text>Reference Text 1</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 2</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 3</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 4</text>
</Ref1>
<Ref1 code="1">
<text>Reference Text 5</text>
</Ref1>
</InvoiceHeader>
</Invoice>


REF2.XML


<?xml version="1.0" encoding="UTF-8"?>
<Invoice>
<InvoiceHeader>
<Ref2 code="2">
<text>Reference Text 1</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 2</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 3</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 4</text>
</Ref2>
<Ref2 code="2">
<text>Reference Text 5</text>
</Ref2>
</InvoiceHeader>
</Invoice>


REF3.XML


<?xml version="1.0" encoding="UTF-8"?>
<Invoice>
<InvoiceHeader>
<Ref3 code="3">
<text>Reference Text 1</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 2</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 3</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 4</text>
</Ref3>
<Ref3 code="3">
<text>Reference Text 5</text>
</Ref3>
</InvoiceHeader>
</Invoice>


REF4.XML


<?xml version="1.0" encoding="UTF-8"?>
<Invoice>
<InvoiceHeader>
<Ref4 code="4">
<text>Reference Text 1</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 2</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 3</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 4</text>
</Ref4>
<Ref4 code="4">
<text>Reference Text 5</text>
</Ref4>
</InvoiceHeader>
</Invoice>


REF5.XML


<?xml version="1.0" encoding="UTF-8"?>
<Invoice>
<InvoiceHeader>
<Ref5 code="5">
<text>Reference Text 1</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 2</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 3</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 4</text>
</Ref5>
<Ref5 code="5">
<text>Reference Text 5</text>
</Ref5>
</InvoiceHeader>
</Invoice>


Bibliography:

Wednesday, January 27, 2010

implementing javax.servlet.ServletContextListener


Each web application has a ServletContext associated with it. The ServletContext object is created when the application is started and is destroyed when the application is shut down. A ServletContext has a global scope and is similar to a global variable in an application. ServletContextListener will gets notified when servlet context gets initialization and destroyed.

A Simple example of implementing javax.servlet.ServletContextListener in your web application is shown below. You need to write one class implementing javax.servlet.ServletContextListener and it's methods. As shown below:

ContextListenerIMPL.java


package com.test;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextListenerIMPL implements ServletContextListener {

/** Creates a new instance of ContextListenerIMPL */
public ContextListenerIMPL() { }

public void contextInitialized(ServletContextEvent servletContextEvent) {

/*
Code which should be executed just after web application context initialized should go here.
This code will be executed before any filter or servlet initialized.
*/

System.out.println("Web Application Context Initialized...");

}

public void contextDestroyed(ServletContextEvent servletContextEvent) {

/*
Code which should be executed just before web application context gets destroyed should go here.
This code will be executed after all filter or servlet in the web application destroyed.
*/

System.out.println("Web Application Context destroyed...");

}

}

Once writting ServletContextListener for your application you need to register it in WEB.XML file of your web application. As shown in bold letters below:

WEB.XML


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
. . . . . .
<listener>
<listener-class>com.test.ContextListenerManager</listener-class>
</listener>

. . . . .
. . . . .
<session-config>
<session-timeout>30</session-timeout>
</session-config>
. . . .
</web-app>



Computer Software And Hardware Information using JAVA


The example provides various information about computer hardware and software. As listed below:
1. OS Installation date & Time
2. OS Serial Number
3. Motherboard Serial Number
4. Processor ID
5. Computer Name

The program provides information as stream of data, It is your JOB how you will extract information from stream and utilize them?


* The program will work only on windows platform and on Windows XP or later OS.

ComputerInfo.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ComputerInfo {

public static void main(String[] args) {

try {

String[][] commands = new String[][]{
{"CMD", "/C", "WMIC OS GET Installdate,SerialNumber"}, //OS Installation date & Time, OS Serial Number
{"CMD", "/C", "WMIC BASEBOARD GET SerialNumber"}, // Motherboadrd Serial Number
{"CMD", "/C", "WMIC CPU GET ProcessorId"}, // Processor ID
{"CMD", "/C", "WMIC COMPUTERSYSTEM GET Name"}}; // Computer Name

for (int i = 0; i < commands.length; i++) {

String[] com = commands[i];

Process process = Runtime.getRuntime().exec(com);

process.getOutputStream().close(); //Closing output stream of the process

System.out.println();
String s = null;
//Reading sucessful output of the command
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((s = reader.readLine()) != null) {
System.out.print(s);
}

// Reading error if any
reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((s = reader.readLine()) != null) {
System.out.print(s);
}

}

} catch (IOException e) {
e.printStackTrace();
}
}
}


Tuesday, December 15, 2009

Invoke Web Service using basic java.net package


Below code shows sample code to invoke Web Service Using basic java.net package.

InvokeService.java



import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
*
* @author tejas
*/

public class InvokeService {

public InvokeService() {

}

public String invoke(String strURL, String soapMessage, String soapAction) {

String resMessage = null;

try {

// Initializing Connection with default properties
URL url = new URL(strURL);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setAllowUserInteraction(true);
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setConnectTimeout(2000); // Setting Connection Timeout
urlCon.setReadTimeout(2000); // Setting Read Timeout
urlCon.setRequestProperty("Action", soapAction); // Setting SOAP Action
urlCon.setRequestProperty("Content-Type", "text/xml"); // Setting Content Type
urlCon.connect();

// Openoutput stream and writting SOAPRequest Message
OutputStream out = urlCon.getOutputStream();
out.write(soapMessage.getBytes());
out.flush();
out.close();

// Reading InputStream
InputStream dataInputStream;
if (urlCon.getResponseCode() == HttpURLConnection.HTTP_OK) {
dataInputStream = urlCon.getInputStream();
} else {
dataInputStream = urlCon.getErrorStream();
}
resMessage = readInputStream(dataInputStream);
dataInputStream.close();

// Disconnecting
urlCon.disconnect();

} catch (Exception ex) {

ex.printStackTrace();

}

return resMessage;

}

private String readInputStream(InputStream in) throws IOException {

StringBuffer sb = new StringBuffer();

int avail = in.available();

while (avail > 0) {
byte[] availBytes = new byte[avail];
in.read(availBytes);
sb.append(new String(availBytes));
avail = in.available();
}

return sb.toString();

}

public static void main(String[] args) {

//Setting Proxy Settings If Applicable
System.setProperty("proxySet", "true");
System.setProperty("http.proxyHost", "192.168.1.100");
System.setProperty("http.proxyPort", "8080");
System.setProperty("http.proxyUser", "ProxyUser");
System.setProperty("http.proxyPassword", "ProxyPassword");

// Web Service URL
String url = "http://www.myapp.com/mywebservice/invoke";

// SOAPAction
String action = "http://www.myapp.com/mywebservice/action";

// SOAPMessage
String reqMessage = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><Request><Emp><EmpNo>10</EmpNo><EmpName>Tejas Purohit</EmpName><EmpDesignation>Developer</EmpDesignation></Emp></Request></soap:Body></soap:Envelope>";

InvokeService invokeService = new InvokeService();

String res = invokeService.invoke(url, reqMessage, action);

// Displaying Response
System.out.println(res);

}
}

Friday, August 21, 2009

XML to HTML Transformation


Below example will take SourceXML.xml(Source XML Block) and HTMLStyleSheet.xsl(StyleSheet to process XML Block) as input. On transform action StyleSheet will process given XML block and store result at Employees.html file.
Before running the Example you need to have following files created as described.

1. HTMLStyleSheet.xsl (given below) as input XSLT.

2. SourceXML.xml (given below) as input XML.

3. Employees.html (an blank file - to avoid FileNotFoundException while transformation) as output file.


SourceXML.xml given below will be used as input XML. It will be transformed to well formed HTML Document after transforming.

SourceXML.xml


<?xml version="1.0"?>
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Kapil dev</Name>
<Address1>Delhi</Address1>
<Address2>India</Address2>
<BirthDate>1954-05-13T00:00:00+05:30</BirthDate>
<Salary>500</Salary>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Sunil Gavaskar</Name>
<Address1>Mumbai</Address1>
<Address2>India</Address2>
<BirthDate>1945-07-10T00:00:00+05:30</BirthDate>
<Salary>700</Salary>
</Employee>
<Employee>
<EmpId>3</EmpId>
<Name>Alen Border</Name>
<Address1>Sydney</Address1>
<Address2>Australia</Address2>
<BirthDate>1950-09-25T00:00:00+05:30</BirthDate>
<Salary>400</Salary>
</Employee>
<Employee>
<EmpId>4</EmpId>
<Name>Sachin Tendulkar</Name>
<Address1>Mumbai</Address1>
<Address2>India</Address2>
<BirthDate>1970-02-06T00:00:00+05:30</BirthDate>
<Salary>2000</Salary>
</Employee>
<Employee>
<EmpId>5</EmpId>
<Name>Ricky Ponting</Name>
<Address1>Melbourne</Address1>
<Address2>Australia</Address2>
<BirthDate>1968-02-15T00:00:00+05:30</BirthDate>
<Salary>1500</Salary>
</Employee>
</Employees>




HTMLStyleSheet.xsl given below will be used as input XSLT. This Style Sheet will transform SourceXML.xml to well formed HTML Document.

HTMLStyleSheet.xsl


<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<HTML>
<BODY>
<h1>
<U>List of Employees</U>
</h1>
<TABLE BORDER="1">
<TBODY>
<TR>
<TH>EmpId</TH>
<TH>Name</TH>
<TH>Address1</TH>
<TH>Address2</TH>
<TH>BirthDate</TH>
<TH>Salary</TH>
</TR>
<xsl:for-each select="Employees">
<xsl:for-each select="Employee">
<TR>
<TD>
<xsl:value-of select="EmpId"/>
</TD>
<TD>
<xsl:value-of select="Name"/>
</TD>
<TD>
<xsl:value-of select="Address1"/>
</TD>
<TD>
<xsl:value-of select="Address2"/>
</TD>
<TD>
<xsl:value-of select="BirthDate"/>
</TD>
<TD>
<xsl:value-of select="Salary"/>
</TD>
</TR>
</xsl:for-each>
</xsl:for-each>
</TBODY>
</TABLE>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>




XmlToHtmlTransformation class contains transform method will accept source xml, source style sheet and output file. It will transform given source xml using style sheet and store result in output file. output file is Employees.html in our case.

XmlToHtmlTransformation.java


import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
*
* @author Tejas Purohit
*/

public class XmlToHtmlTransformation {

public boolean transform(String stylesheet, String sourceXML, String result) {

try {

// Creating Transformer with XSLT
Source sourceXSLT = new StreamSource(new FileInputStream(stylesheet));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(sourceXSLT);

Source streamSource = new StreamSource(new FileInputStream(sourceXML)); // Creating StreamSource with sourceXML
Result streamResult = new StreamResult(new FileOutputStream(result)); // Creating StreamResult with result

transformer.transform(streamSource, streamResult); // Transforming

} catch (Exception exception) {

exception.printStackTrace();

return false;

}

return true;
}

public static void main(String[] args) {

XmlToHtmlTransformation xhTransformation = new XmlToHtmlTransformation();

String stylesheet = "HTMLStyleSheet.xsl";
String sourceXML = "SourceXML.xml";
String result = "Employees.html";

if (xhTransformation.transform(stylesheet, sourceXML, result)) {
System.out.println("Successful.");
} else {
System.out.println("Error.");
}
}
}




Transformation process will generate result HTML and store in Employees.html. Once Transformation is done Employees.html will look like below:

Employees.html


<HTML>
<BODY>
<h1>
<U>List of Employees</U>
</h1>
<TABLE BORDER="1">
<TBODY>
<TR>
<TH>EmpId</TH><TH>Name</TH><TH>Address1</TH><TH>Address2</TH><TH>BirthDate</TH><TH>Salary</TH>
</TR>
<TR>
<TD>1</TD><TD>Kapil dev</TD><TD>Delhi</TD><TD>India</TD><TD>1954-05-13T00:00:00+05:30</TD><TD>500</TD>
</TR>
<TR>
<TD>2</TD><TD>Sunil Gavaskar</TD><TD>Mumbai</TD><TD>India</TD><TD>1945-07-10T00:00:00+05:30</TD><TD>700</TD>
</TR>
<TR>
<TD>3</TD><TD>Alen Border</TD><TD>Sydney</TD><TD>Australia</TD><TD>1950-09-25T00:00:00+05:30</TD><TD>400</TD>
</TR>
<TR>
<TD>4</TD><TD>Sachin Tendulkar</TD><TD>Mumbai</TD><TD>India</TD><TD>1970-02-06T00:00:00+05:30</TD><TD>2000</TD>
</TR>
<TR>
<TD>5</TD><TD>Ricky Ponting</TD><TD>Melbourne</TD><TD>Australia</TD><TD>1968-02-15T00:00:00+05:30</TD><TD>1500</TD>
</TR>
</TBODY>
</TABLE>
</BODY>
</HTML>


Thursday, August 13, 2009

Garbage Collection in JavaScript


     Rich application development now a days includes wast use of JavaScript and Ajax. Latest web browsers are developed to handle such interactive web applications. All data which Ajax imports from server is stored in web browser memory cache. Larger amount of data stored in web browser cache may slow down performance of web browser. One way to release memory from web browser cache or applying garbage collection is to close the browser. But web application can't use this practice to close browser or tell user to restart web browser while web application application is running.

     You can force/implement garbage collection in JavaScript. Web developers should develop practice to force garbage collection contentiously while web application is running.

     delete operator is one of the most unknown and unused operators in JavaScript. You can use delete operator to release memory occupied by any unused or unreferenced objects in JavaScript. While deleting any object be sure you don't have any reference stored in any other variables for particular object. This will lead performance breakdown when these other variable will try to access the object which was deleted. You can delete any object which has performed it's job and is not going to be used in future.

     For example, You can delete window onload handler function and release any memory associated with the function, like this:


var winLoadFun = function()
{
// code for my function
delete winLoadFun;
}

window.addEventListener('load', winLoadFun , false);


Wednesday, August 12, 2009

Indent XML


Below Code Indent or Organize plain or unorganized XML String using XML API in JDK 6.

IndentXML.java



import com.actl.dxchange.utilities.XMLUtil;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.*;

/**
* XMLTransformations Utilities.
* @author Tejas Purohit
*/
public class IndentXML {

public IndentXML() {

}

/**
* Indent given XML String and returns organized String.
* @param strXML Plain XML String
* @return Organized or indented String
*/
public String indentXML(String strXML) {

String result = null;

try {

// Creating StreamSource from given plain XML String
ByteArrayInputStream bin = new ByteArrayInputStream(strXML.getBytes());
StreamSource streamSource = new StreamSource(bin);
streamSource.setSystemId("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");

// Creating new Transformer
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();

// Setting output properties
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD XHTML 1.1//EN");


// Creating StreamResult
ByteArrayOutputStream bout = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult(bout);
streamResult.setSystemId("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");

// Transforming StreamSource and storing result in StreamResult
transformer.transform(streamSource, streamResult);

// Getting String from ByteArrayOutputStream
result = bout.toString();

} catch (Exception ex) {

ex.printStackTrace();

}

return result;

}

public static void main(String[] args) throws Exception {

IndentXML t = new IndentXML();

String strXML = "<Employees><Employee Name='Amitabh Bachapan' Designation='Director'>"+
"<Address><AddressLine>Opp. Taj Square</AddressLine><City>Mumbai</City>"+
"<Country>India</Country></Address></Employee><Employee Name='Shah RukRukKhan'"+
" Designation='Manager'><Address><AddressLine>Behind Chandani Choak</AddressLine>"+
"<City>Delhi</City><Country>India</Country></Address></Employee></Employees>";

System.out.println("Plain XML:");
System.out.println(strXML);

strXML = t.indentXML(strXML);

System.out.println("Organized XML:");
System.out.println(strXML);

}
}

/*
Programme Output:

Plain XML:
<Employees><Employee Name='Amitabh Bachapan' Designation='Director'><Address><AddressLine>Opp. Taj Square</AddressLine><City>Mumbai</City><Country>India</Country></Address></Employee><Employee Name='Shah RukRukKhan' Designation='Manager'><Address><AddressLine>Behind Chandani Choak</AddressLine><City>Delhi</City><Country>India</Country></Address></Employee></Employees>


Organized XML:

<!DOCTYPE Employees PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<Employees>
<Employee Name="Amitabh Bachapan" Designation="Director">
<Address>
<AddressLine>Opp. Taj Square</AddressLine>
<City>Mumbai</City>
<Country>India</Country>
</Address>
</Employee>
<Employee Name="Shah RukRukKhan" Designation="Manager">
<Address>
<AddressLine>Behind Chandani Choak</AddressLine>
<City>Delhi</City>
<Country>India</Country>
</Address>
</Employee>
</Employees>
*/