I know that I can create xml
files programmatically by using DOM
api in java like the following:
DocumentBuilderFactory do
You can create an XSLT the same way you create an XML file, since XSLTs are XML files.
However, if you have to deal with XML/XSLT transformations a lot, Apache Cocoon 3 has a very lightweight XML/XSLT pipeline system to use as a library instead of dealing with all XML dom stuff and XSLT transformations manually.
DOM is a pretty cumbersome way of creating XML.
There's a far better way - use XSLT.
The more complex the XML, the bigger the win from using XSLT rather than DOM to create it.
There's no reason why you can't use XSLT to create XSLT (there's even a special declaration xsl:namespace-alias to make it a little bit easier - searching for xsl:namespace-alias will show up examples of its use.
Since XSLT it's XML too, you can simply use the same strategy:
...
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("xsl:stylesheet");
// adding attributes like namespaces etc...
document.appendChild(rootElement);
Element em = document.createElement("xsl:template");
em.setAttribute("match", "/");
and so on...
But it's not very elegant. You should use a library or a framework instead, you should easily find one googling around.