As always everything is hard if you don't know how to do it, but if you know then it turns out to be very simple.
First you have to read in your file. For the convenience I assume you know how to do that. In my case: I read in my XML document after I have generated it by parsing an Pl/Sql package from file. But maybe in a later phase I'm going to read it from the database.
Then you have to parse it. That's done as follows:
XMLDocument xmlDoc;
String myXmlString = "
DOMParser parser = new DOMParser();
InputSource inputStream = new InputSource();
inputStream.setCharacterStream(new StringReader(myXmlString);
parser.parse(inputStream);
xmlDoc = parser.getDocument();
Not to hard, is it? You have to do this for both your XML-Document and your XSL-Document.
The code is simply:
- Instantiate a parser
- Create an inputStream from the input XML String (an xsl-stylesheet is in fact also an xml-document).
- Execute the parser
- Get a DOM Document (Document Object Model) from the parser.
String transform(XMLDocument xslDoc, XMLDocument xmlDoc) {
XSLProcessor xslProcessor = new XSLProcessor();
XSLStylesheet xslt;
String result = "";
try {
xslt = xslProcessor.newXSLStylesheet(xslDoc);
XMLDocumentFragment fragment;
xslProcessor.setXSLTVersion(xslProcessor.XSLT20);
xslProcessor.showWarnings(true);
xslProcessor.setErrorStream(System.err);
fragment = xslProcessor.processXSL(xslt, xmlDoc);
result = fragment.getText();
} catch (XSLException e) {
pl(e.toString());
} catch (IOException e) {
pl(e.toString());
}
return result;
}
This piece of code does the following:
- instantiates a XSL Processor;
- create a xslstylesheet from the stylesheet in the xmldocument (that you parsed with the previous piece of code);
- set some parameters of the processor: XSL-version, warnings, error-stream to output errors;
- process the xslstylesheet, which delivers an xmlfragment (the Oracle XML parser can also output to a URI, but I want to have a string)
- at the end get the String document from the xml-fragment
To use the Oracle XML parser you need the following imports:
import oracle.xml.parser.v2.XMLDocument;
import oracle.xml.parser.v2.XMLDocumentFragment;
import oracle.xml.parser.v2.XSLException;
import oracle.xml.parser.v2.XSLProcessor;
import oracle.xml.parser.v2.XSLStylesheet;
And of course add the "Oracle XML Parser v2" to your jDeveloper project or add the xmlparserv2.jar and xml.jar files to your class path.
0 comments:
Post a Comment