简体   繁体   中英

Java Translate XML into HTML using XSL

I used JAXB to create a very complicated .xml file which I saved on the drive. I also manually made an .xsl file which is my template.

How do I now programmatically use the above two to create an html output file ?

I tried various things and maybe I'm just tired but I can't even successfully open the .xml file into a Document .

Does someone have a working example ? I would greatly appreciate it! Thanks :)

I tried various things, including the official code examples but I can't find a working example. Nothing but null pointer exceptions. :(

The smallest working example I can give you:

import java.io.File;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class UseXMLToHTML {

    public static void main(String[] args) throws TransformerException {
        StreamResult result = new StreamResult(new File("output.html"));
        StreamSource source = new StreamSource(new File("input.xml"));
        StreamSource xslt = new StreamSource(new File("transform.xslt"));

        Transformer transformer = TransformerFactory.newInstance().newTransformer(xslt);

        transformer.transform(source, result);
    }
}

This would probably do the trick;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class TestMain {
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Source xslt = new StreamSource(new File("transform.xslt"));
        Transformer transformer = factory.newTransformer(xslt);

        Source text = new StreamSource(new File("input.xml"));
        transformer.transform(text, new StreamResult(new File("output.xml")));
    }
}

Consider trying out stuff from these urls:

http://www.w3schools.com/xsl/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog

http://www.w3schools.com/xsl/tryxslt_result.asp?xmlfile=cdcatalog&xsltfile=cdcatalog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM