Applying XSLT onto XML files [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Applying XSLT v. 2 on XML
I have a Directory structure with XML files. I am having an XSLT 1.0 which I am applying on all these files and generating new XML files for each. I had written code in JAVA. But my problem is I am not able to put output files at a separate output folder having same structure as one from which I am taking my input XML file. For Example if I have a root directory Home with two folders Folder1 and Folder2. Each Folder1 & Folder2 has number of XML files. So when I convert my XML files present in these folders so the output files so generated should go in separate folder having same structure.
Here is the Java code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XMLwithXSLT {
public static void main(String[] args) throws FileNotFoundException,
TransformerConfigurationException, TransformerException {
File dir = new File("Input Directory Root Path Here");
listFilesInDirectory(dir);
}
public static void listFilesInDirectory(File dir) throws FileNotFoundException,
TransformerException {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
System.out.println(f.getName());
listFilesInDirectory(f);
} else {
System.out.println(f.getName());
OutputXml(f);
}
}
}
public static void OutputXml(File in) throws FileNotFoundException,
TransformerException{
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource("backup.xslt");
Source xmlDoc = new StreamSource(in.getPath()) ;
System.out.print(in.getName() + "/n");
String outputFileName = in.getName();
System.out.print(outputFileName );
OutputStream htmlFile;
htmlFile = new FileOutputStream(outputFileName);
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlFile));
}
}
So can anyone help me as how I can specify the output path for the generated new file? Also how I can generate a output files in the same directory format as input?

You should add the path to your output dir. For example:
String outputFileName = "c:\\tmp\\xmloutput\\" + in.getName();
So basicaly, loop your input files and take over subdir and file name. See if it exists in your output directory and if not create it. And if zo, then name your outputFileName this way.

What i got from your question is , There are two folders Folder1 and Folder2. Folder1 Have some XML file and Folder2 have some XML file. Lets consider you have got the output for all xml file present in Folder1 to HTML format. and Now you want those HTML files to be present in a folder called Folder1 some where in your system(or lets consider the temp folder of the system).and same for all the XML files present in Folder2.
If you want this kind of output then update the code with following
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XMLwithXSLT {
static String pathRequiredForFile=null;
static String tempfolder=System.getProperty("java.io.tmpdir");
public static void main(String[] args) throws FileNotFoundException,
TransformerConfigurationException, TransformerException {
File dir = new File("Input Directory Root Path Here");
listFilesInDirectory(dir);
}
public static void listFilesInDirectory(File dir) throws FileNotFoundException,
TransformerException {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
pathRequiredForFile=f.getName();
listFilesInDirectory(f);
} else {
System.out.println(f.getName());
File path=new File(tempfolder+"//"+pathRequiredForFile);
path.mkdir();
OutputXml(f,path.getAbsolutePath());
}
}
}
}
public static void OutputXml(File in,String saveFileInPath) throws FileNotFoundException,
TransformerException{
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource("backup.xslt");
Source xmlDoc = new StreamSource(in.getPath()) ;
System.out.print(in.getName() + "/n");
String outputFileName = in.getName().split("\\.")[0];
System.out.println(outputFileName );
OutputStream htmlFile;
htmlFile = new FileOutputStream(saveFileInPath+"//"+outputFileName+".html");
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlFile));
}
}

Related

How do I create a single JAR file to move specific files in a folder to another directory?

I created a Java program which basically moves all files within a specific "test" folder to a completely different and specific directory on the computer. How can I package the "test" folder, and both the java and class files into a single runnable JAR file?
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import javax.swing.JOptionPane;
public class Test
{
public static void main(String[] args) throws IOException
{
File sourceFolder = new File("test");
String dataFolder = System.getenv("APPDATA");
File destinationFolder = new File(dataFolder + "\\testing");
copyFolder(sourceFolder, destinationFolder);
}
private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException
{
if (sourceFolder.isDirectory())
{
if (!destinationFolder.exists())
{
destinationFolder.mkdir();
}
String files[] = sourceFolder.list();
for (String file : files)
{
File srcFile = new File(sourceFolder, file);
File destFile = new File(destinationFolder, file);
copyFolder(srcFile, destFile);
}
JOptionPane.showMessageDialog(null,"File installed successfully","Title",1);
}
else
{
Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
I get this error I get when I move the test folder:
Exception in thread "main" java.nio.file.NoSuchFileException: test
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileCopy.copy(WindowsFileCopy.java:98)
at java.base/sun.nio.fs.WindowsFileSystemProvider.copy(WindowsFileSystemProvider.java:283)
at java.base/java.nio.file.Files.copy(Files.java:1298)
at Test.copyFolder(test.java:39)
at Test.main(test.java:16)

Copying file using Apache Commons FileUtils

On the first run, I want to copy the given File to a new location with a new file name.
Every subsequent run should overwrite the same destination file created during first run.
During first run, the destination file does not exist. Only the directory exists.
I wrote the following program:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
However, this throws null pointer exception on the following line:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
What am I missing?
Directory someDir is directly under my project's root directory in eclipse.
Both source files myFile.txt and myFile_Another.txt exists directly under my project's root directory in eclipse.
I used this and it works as I am expecting:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
Using Java nio.

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

Files.copy throws java.nio.file.NoSuchFileException even though the file to be copied definitely exists

I have a problem with a seemingly simple application.
What it should do:
-Read out the files (*.jpg) of a (hardcoded) directory
-Use the contained Metadata (gotten via implemented Libraries) of said jpgs to generate directories (./year/month/)
-copy the files into the corresponding directories.
What it doesn't:
-copy the files into the corresponding directories BECAUSE it doesn't find the original files (which it read out itself previously). I honestly have no clue why that is.
Here the sourcecode:
package fotosorter;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifIFD0Directory;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
public class Fotosorter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws JpegProcessingException, IOException {
File startdir = new File(System.getProperty("user.dir"));
FileFilter jpg = new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getAbsoluteFile().toString().toLowerCase().endsWith(".jpg");
}
};
File dir = new File(startdir, "bitmaps"+File.separator+"java-temp");
if (!(dir.exists() && dir.isDirectory())) {
if (!dir.mkdir()) {
throw new IOException("kann das Verzeichnis nicht erzeugen ");
}
}
File[] files = new File(startdir, "" + File.separator + "bitmaps" + File.separator + "java-fotos").listFiles(jpg);
for (File file : files) {
Metadata metadata = JpegMetadataReader.readMetadata(file);
ExifIFD0Directory directory = metadata.getDirectory(ExifIFD0Directory.class);
String[] dates = directory.getDate(ExifIFD0Directory.TAG_DATETIME).toString().split(" ");
File year = new File(dir, dates[5]);
File month = new File(year, dates[1]);
File fname = new File(month, file.getName());
if (!(month.getParentFile().exists() && month.getParentFile().isDirectory())) {
if (!month.mkdirs()) {
throw new IOException("kann die Verzeichnisse nicht erzeugen");
}
}
copyFile(file, fname);
}
}
public static void copyFile(File from, File to) throws IOException {
Files.copy(from.toPath(), to.toPath());
}
}
And here the full exception it throws:
run:
Exception in thread "main" java.nio.file.NoSuchFileException: D:\Benutzerdaten\Paul\Documents\NetBeansProjects\Fotosorter\bitmaps\java-fotos\cimg2709.jpg -> D:\Benutzerdaten\Paul\Documents\NetBeansProjects\Fotosorter\bitmaps\java-temp\2008\Sep\cimg2709.jpg
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsFileCopy.copy(WindowsFileCopy.java:205)
at sun.nio.fs.WindowsFileSystemProvider.copy(WindowsFileSystemProvider.java:277)
at java.nio.file.Files.copy(Files.java:1225)
at fotosorter.Fotosorter.copyFile(Fotosorter.java:64)
at fotosorter.Fotosorter.main(Fotosorter.java:59)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
As you may have guessed it's not finished yet. Apart from solving my previously stated problem I still have to put it into methods.
Make sure that the input file exists.
But also make sure that the path of the destination folder does exist.

Jar FileNotFoundException caused by write to a xml File

I am trying to write to a XML file. It runs correctly in eclipse. The file is located at ca/ism/wen/domain folder (together with my user.java). However, it is throws FileNotFoundException when I run the exported runnable jar file. Is there way to write to an xml file in the jar file? Following is my code.
package ca.ism.wen.utils;
import java.io.File;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import ca.ism.wen.domain.User;
/**
* Load XML file
*
*/
public class XmlFactory {
private static Document dom;
//private static File file = new File(User.class.getResource("UserRDP.xml").getPath());
private static InputStream filei = User.class.getResourceAsStream("UserRDP.xml");
private static File fileo = new File(User.class.getResource("UserRDP.xml").getPath());
static {
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(filei);
} catch (Exception e){
e.printStackTrace();
}
}
public static Document getDom(){
return dom;
}
public static void saveDom(){
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
DOMSource ds = new DOMSource(dom);
StreamResult sr = new StreamResult(fileo);
trans.transform(ds, sr);
} catch (Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
}
If I have to put my XML file externally somewhere, I want to get a runnable file and put it in a folder under my whole project (just like normal software), cause it may be deployed to other person's machine later. Is that possible?
I believe you need to provide an implementation for javax.xml.parsers.DocumentBuilderFactory as a third party library to your classpath as per the javadoc.
Try
new File(User.class.getResource("UserRDP.xml").toURI());
The appropriate constructor of the File should be used to locate the resource. This approach only works with exploded jar. You cannot write to a jar, however you can read from it using jar protocol.

Categories

Resources