XML Parsing
Hi All,
I am new to XML and XML parsing.
I am having a task of taking a XML file and to generate report in HTML.
What i found out is i can have one XML file and i have to have a XSL
file for it.
Then i have to take XML and XSL as source and generate the HTML result.Can anyone please explain how to proceed with it.
# 3
Download Xalan from Apache. Then, place xalan.jar (along with xml-apis.jar) on your CLASSPATH and use something like the following:
public final class XslTransformer extends Object {
/////////////////////
// Class Variables //
/////////////////////
private static final Map<String, Templates> STYLESHEET_CACHE;
private static final TransformerFactory FACTORY;
//////////////////
// Constructors //
//////////////////
static {
STYLESHEET_CACHE = new HashMap<String, Templates>();
FACTORY = TransformerFactory.newInstance();
}
private XslTransformer() {
super();
}
////////////////////
// Public Methods //
////////////////////
public static final void transform(final String uriXsl, final InputStream xml, final OutputStream target) {
Templates xslTemplates = getTemplates(uriXsl);
Transformer transformer = null;
try {
transformer = xslTemplates.newTransformer();
}
catch (TransformerConfigurationException fatal) {
throw new ConfigurationError("Unable to create XSL transformer", fatal);
}
try {
transformer.transform(new StreamSource(xml), new StreamResult(target));
}
catch (TransformerException e) {
throw new ParseError("Unable to transform XML using XSL stylesheet", e);
}
}
/////////////////////
// Private Methods //
/////////////////////
private static Templates getTemplates(final String uri) {
Templates templates = STYLESHEET_CACHE.get(uri);
if (templates != null) {
return templates;
}
InputStream in = XslTransformer.class.getResourceAsStream(uri);
if (in == null) {
try {
in = new FileInputStream(uri);
}
catch (FileNotFoundException fatal) {
throw new ConfigurationError("Unable to locate XSL stylesheet at '" + uri + "'", fatal);
}
}
try {
templates = FACTORY.newTemplates(new StreamSource(in));
}
catch (TransformerConfigurationException fatal) {
throw new ConfigurationError("Unable to parse XSL templates from '" + uri + "'", fatal);
}
STYLESHEET_CACHE.put(uri, templates);
return templates;
}
}
- Saish