Archive for the ‘xml’ tag
XSL Transform using Java
import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; ... // The XSL source: StreamSource xsl = new StreamSource(...); // Create the transformer: TransformerFactory factory = TransformerFactory.newInstance(); Templates template = factory.newTemplates(xsl); // can throw TransformerConfigurationException (parent exception is: TransformerException) Transformer transformer = template.newTransformer(); // can throw TransformerConfigurationException // The data XML source StreamSource data = new StreamSource(...); // The transformed output: StreamResult out = new StreamResult(...); // Transform using the Transformer instance: transformer.transform(data, out); // can throw TransformerException
Have a look at the StreamSource API and StreamResult API to understand the various ways by which it can be instantiated.
XPath in Java: Code Snippet
try{
InputStream is = ...;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
is.close();
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
XPathExpression xpr = xpath.compile("/executors/executor");
NodeList nodes = (NodeList)xpr.evaluate(doc, XPathConstants.NODESET);
int size = nodes.getLength();
for(int i=0; i<size; i++){
NamedNodeMap nnm = nodes.item(i).getAttributes();
String strPath = nnm.getNamedItem("path").getNodeValue();
String strClass = nnm.getNamedItem("class").getNodeValue();
print("Path / Class: " + strPath + " / " + strClass);
}
} catch(ParserConfigurationException ex){
print(ex.getMessage());
} catch(SAXException ex){
print(ex.getMessage());
} catch(IOException ex){
print(ex.getMessage());
} catch(XPathExpressionException ex){
print(ex.getMessage());
}
XOM 1.2.1 Released
Linux command-line XSLT
To convert an XML based on a XSL, use this command:
$ xsltproc /path/to/xsl.xsl /path/to/xml.xml
The converted document will be written to STDOUT. To write to a particular file, you may use the -o parameter:
$ xsltproc /path/to/xsl.xsl /path/to/xml.xml -o out.html
Check the info/man pages for additional information.