Click here to Skip to main content
15,388,998 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi all !
I have a problem here, I try to convert my file csv en XML with this code :

Java
<pre>public class conversion {
    public static void main(String[] args) {
        new conversion();
    }


    public class XMLCreators {
        // Protected Properties

        protected DocumentBuilderFactory domFactory = null;
        protected DocumentBuilder domBuilder = null;

        public XMLCreators() {
            try {
                domFactory = DocumentBuilderFactory.newInstance();
                domBuilder = domFactory.newDocumentBuilder();
            } catch (FactoryConfigurationError exp) {
                System.err.println(exp.toString());
            } catch (ParserConfigurationException exp) {
                System.err.println(exp.toString());
            } catch (Exception exp) {
                System.err.println(exp.toString());
            }
        }

        public int convertFile(String csvFileName, String xmlFileName, char delimiter) {

            int rowsCount = -1;
            BufferedReader csvReader;
            try {
                Document newDoc = domBuilder.newDocument();
                // Root element
                Element rootElement = newDoc.createElement("XMLCreators");
                newDoc.appendChild(rootElement);
                // Read csv file
                csvReader = new BufferedReader(new FileReader(csvFileName));

                //** Now using the OpenCSV **//
                CSVParser parser = new CSVParserBuilder()
                        .withSeparator(delimiter)
                        .build();

                CSVReader reader = new CSVReaderBuilder(new FileReader(csvFileName))
                        .withCSVParser(parser)
                        .build();
                //CSVReader reader = new CSVReader(csvReader);
                String[] nextLine;
                int line = 0;
                List<String> headers = new ArrayList<String>(5);
                while ((nextLine = reader.readNext()) != null) {
                    if (line == 0) { // Header row
                        for (String col : nextLine) {
                            headers.add(col);
                        }
                    } else { // Data row
                        Element rowElement = newDoc.createElement("row");
                        rootElement.appendChild(rowElement);

                        int col = 0;
                        for (String value : nextLine) {
                            String header = headers.get(col).replaceAll("[\\t\\p{Zs}\\u0020]", "_");

                            Element curElement = newDoc.createElement(header);
                            curElement.appendChild(newDoc.createTextNode(value.trim()));
                            rowElement.appendChild(curElement);

                            col++;
                        }
                    }
                    line++;
                }
                //** End of CSV parsing**//

                FileWriter writer = null;

                try {

                    writer = new FileWriter(new File(xmlFileName));

                    TransformerFactory tranFactory = TransformerFactory.newInstance();
                    Transformer aTransformer = tranFactory.newTransformer();
                    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                    aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

                    Source src = new DOMSource(newDoc);
                    Result result = new StreamResult(writer);
                    aTransformer.transform(src, result);

                    writer.flush();

                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (Exception e) {
                    }
                }

                // Output to console for testing
                // Resultt result = new StreamResult(System.out);
            } catch (IOException exp) {
                exp.printStackTrace();
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            return rowsCount;
            // "XLM Document has been created" + rowsCount;
        }
    }
}

But I don't know why but I can't make it work with this code too :
Java
public class Menu implements ActionListener{
	JFrame f = new JFrame();
	char t;
	  public Menu() {

	    WindowListener l = new WindowAdapter() {
	      public void windowClosing(WindowEvent e){
	        System.exit(0);
	      }
	    };
	    f.addWindowListener(l);
	    //Modelisation du bouton pour convertir le fichier
	    JButton btn_fichier = new JButton("Cliquez pour choisir votre fichier à convertir");
	    btn_fichier.setFont(new Font("Sherif", Font.BOLD, 14));
	    JMenuBar menu = new JMenuBar();
	    JMenu help = new JMenu("Aide");
	    JMenuItem e = new JMenuItem("?");
	    menu.add(e);
	    help.add(e);
	    help.addActionListener(this);
	    btn_fichier.setBounds(140,185,450,30);
	    btn_fichier.setForeground(Color.BLACK);
	    btn_fichier.addActionListener(this);
	    f.add(btn_fichier);
	    menu.add(help);
	    f.add(menu);
	    f.pack();
	    f.setSize(700,500);
	    f.setLayout(null);
	    f.setVisible(true);
	    f.setResizable(false);
	  }
	  public void actionPerformed(ActionEvent e) {
		    String s = e.getActionCommand();
		    
		    if (s.equals("Cliquez pour choisir votre fichier à convertir")) {
		    	JFileChooser fichier = new JFileChooser( FileSystemView.getFileSystemView().getHomeDirectory());
		    	fichier.setDialogTitle("Choississez votre fichier .csv");
		    	fichier.setAcceptAllFileFilterUsed(false);
		    	FileNameExtensionFilter filter = new FileNameExtensionFilter("Fichier .csv","csv");
		    	fichier.addChoosableFileFilter(filter);
		    	int res = fichier.showOpenDialog(null);
		        // Enregistrez le fichier
		        if (res == JFileChooser.APPROVE_OPTION) {
		          File file = fichier.getSelectedFile();
		          String fi = fichier.getName(file);
		          conversion.XMLCreators.convertFile(file, xml, t);
		          		
		        }
		     ;
		      
		    }
		    if (e.getSource().equals("?")) {
		    	System.out.println("Vous devez cliquer sur le bouton du milieu et joindre un fichier .csv, le fichier"
		    			+ "se telechargera converti en .xml sur votre PC directement");
		    }
	  }
}


What I have tried:

I tried to modify some lines of the code, and also to modify "file" into String but it's complicated.
After I click on the button "Validate" of the Window of JFileChooser, I want my file converted in XML and downloaded on my computer.
But I have an error, "No enclosing instance of type conversion. Must Qualify the allocation instance of type conversion." (for the line 71 of my second code given).
I tried many things : changing the type of my entries, put in void or static my functions...
I just don't know how to solve the problem.
This is why I'm here!

Someone could help me with this?
Thank a lot !
Posted
Updated 28-Jun-22 4:49am
v2
Comments
OriginalGriff 24-Jun-22 7:17am
   
And?
What does it do that you didn't expect, or not do that you did?
What have you tried to do to find out why?
Are there any error messages, and if so, where and when? What did you do to make them happen?

This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with.
Use the "Improve question" widget to edit your question and provide better information.
Caramelwilly57 24-Jun-22 8:01am
   
Oh sorry, you are right. It is not clear at all. Really Sorry.
Let me explain more here so.
After I click on the button "Validate" of the Window of JFileChooser, I want my file converted in XML and downloaded on my computer.
But I have an error, "No enclosing instance of type conversion. Must Qualify the allocation instance of type conversion." (for the line 71 of my second code given).
I tried many things : changing the type of my entries, put in void or static my functions...
I just don't know how to solve the problem.
This is why I'm here!
I hope it's more detailled now and again, sorry !

The method convertFile is expecting three arguments, two strings and a char. When you call it in your menu class, you call: conversion.XMLCreators.convertFile(file, xml, t);
The variable "file" is a "File" object type - perhaps you meant the variable "fi" ?
The variable "xml" is not declared or initialized
- declare this as a string and set it to the output file name you want
The variable "t" is declared a char in line 3 of Menu but not initialized.
- initialize it to the character "," (assuming you want comma as the delimiter)

You may have other problems but you have to fix these first.
   
Comments
Caramelwilly57 27-Jun-22 5:01am
   
Hi!
First, thank for your response ! It helped me.
I have still few questions.
I have initialized my char t (char t = ',';) and declared xml (String XML; XML=null;)
For file, I really want the file to be converted and not just the name, I'm scared that if I put "fi" it will convert just the name of my file.
Now I have no error if i put (XMLCreators xmlCreators = new XMLCreators(); xmlCreators.convertFile(fi,XML,t); but when I try to run it, I have so many errors in my console, and the first one is "The specified file was not found".
I don't know why.
Thank for your help!
Williams
matblue25 27-Jun-22 12:31pm
   
You have to look at and understand all of the code in the convertFile method. The arguments for convertFile are: String csvFileName, String xmlFileName and char delimiter. Look at how those variables get used in the method. The only use of csvFileName is to create csvReader as a BufferedReader object. All it does is read the file. Don't be "afraid" of the code - understand it. In any case, if you're worried that the file might get destroyed or changed, save a copy of it somewhere else and work with the copy. That's not unusual. If you're developing and testing some code that will permanently change some thing, you're better off working with copies of the thing as you're testing your code, at least until you're sure it's working correctly.
As far as how the convertFile method uses the string xmlFileName, I'm going to let you do the work rather than just tell you but LOOK AT THE CODE! The variable is declared as a string for a reason! Look at what convertFile does with that string. Hint: you're going to want to set xml to something like "outputfile.xml".
If you pass objects other than what a method expects, you're going to get all kinds of strange error messages because it will not know what to do with them. When calling a method, you have to give the method EXACTLY what it's looking for - not what you think it ought to use. Look at the code in the method to see what it uses the arguments for. Don't assume.
Learn to use the debugger and step through the code one line at a time and look at the values of the variables as you go along. You can't be an accomplished software developer without being an expert at debugging. It's like trying to be a carpenter without knowing how to use a saw.
Caramelwilly57 28-Jun-22 10:47am
   
Thank !
I correctly read the code I think it's better now !
I just have 1 error but I don't understand why.
The classical error "java.lang.NullPointerException".
I know what the error means, so I don't understand why. It's like my class "conversion" is executed first and not my Menu class, and so my "csvReader" or "csvFileName" is null. But I specified these object thanks to JFileChooser.
I tried to put the JFileChooser in my conversion class just to see what it does, but nothing.
Also, I put some "System.out.println(csvReader) and System.out.println(csvFileName) to see what they are pointing at but it's always null.
I will add a solution for you to see better my codes right now.
Thank for your help !
matblue25 28-Jun-22 12:09pm
   
You're setting the string variable "XML" to Null then calling your convertFile method passing it as the 2nd argument. The first time you use the 2nd argument in the convertFile method is:
writer = new FileWriter(new File(xmlFileName));

So, you're trying to create a new File with a null string. That's not going to work. You didn't take my hint in my earlier message. Just try setting XML = "outputfile.xml"; in the initialize method.
Caramelwilly57 29-Jun-22 3:22am
   
Oh I did not understand your hint like this sorry, my bad.
I'm back with the error "file was not found".
I will look at it closer, with your hint, and come back if I have some questions.
Thank a lot, it helped me a lot!

Caramelwilly57 29-Jun-22 7:33am
   
Hey.
I solved my problems, but now I have an error (I hope it's the last aha) : "INVALID_CHARACTER_ERR : an invalid or illegal XML character is specified".
I looked on the internet what was that error.
Mainly, it's because XML characters can't have spaces in their names.
So I looked my codes an verify about the spaces.
I deleted some but it's still the same error.
Apparently the error is line 97 "Element curElement = newDoc.createElement(header);" but it seems right.
Thank for your help!
matblue25 29-Jun-22 15:56pm
   
I don't think I can help with that. I'd recommend you step through the code in the debugger and look at the value of "header" when the error occurs and compare that to what the documentation of the "createElement" method requires in org.w3c.dom.Document. I looked at the method and it says the INVALID_CHARACTER_ERR is raised if the specified name is not an XML name according to the XML version in use specified in the Document.xmlVersion attribute. So something is wrong with the value of "header".
According to W3C:
XML elements must follow these naming rules:
Element names are case-sensitive.
Element names must start with a letter or underscore.
Element names cannot start with the letters xml (or XML, or Xml, etc)
Element names can contain letters, digits, hyphens, underscores, and periods.
Element names cannot contain spaces.

Seems pretty simple. You must be violating one of these requirements.
first class Menu (renamed fenetre here)
<pre lang="Java">
package image;

import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Window.Type;

import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

import com.opencsv.exceptions.CsvException;

//import image.conversion.XMLCreators;

import java.awt.Button;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.awt.event.ActionEvent;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class fenetre extends conversion {
	//char t = ',';
	private JFrame frmFaiaPourFidexpert;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					fenetre window = new fenetre();
					window.frmFaiaPourFidexpert.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public fenetre() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmFaiaPourFidexpert = new JFrame();
		frmFaiaPourFidexpert.setBackground(new Color(245, 222, 179));
		frmFaiaPourFidexpert.setTitle("FAIA pour FID-Expert");
		frmFaiaPourFidexpert.setForeground(Color.BLACK);
		frmFaiaPourFidexpert.setIconImage(Toolkit.getDefaultToolkit().getImage(fenetre.class.getResource("/image/lux.png")));
		frmFaiaPourFidexpert.setBounds(100, 100, 470, 440);
		frmFaiaPourFidexpert.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmFaiaPourFidexpert.setResizable(false);
		
		JButton btnNewButton = new JButton("Convertir un fichier");
		btnNewButton.setBounds(0, 302, 456, 29);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String s = e.getActionCommand();
			    
			    if (s.equals("Convertir un fichier")) {
			    	JFileChooser fichier = new JFileChooser( FileSystemView.getFileSystemView().getHomeDirectory());
			    	fichier.setDialogTitle("Choississez votre fichier .csv");
			    	fichier.setAcceptAllFileFilterUsed(false);
			    	FileNameExtensionFilter filter = new FileNameExtensionFilter("Fichier .csv","csv");
			    	fichier.addChoosableFileFilter(filter);
			    	int res = fichier.showOpenDialog(null);
			        // Enregistrez le fichier
			        if (res == JFileChooser.APPROVE_OPTION) {
			          String XML;
			          XML = null;
			          
			          //File file = fichier.getSelectedFile();
			          String fi = fichier.getName();
			          XMLCreators xmlCreators = new XMLCreators();
					  xmlCreators.convertFile(fi, XML, '\t');
			          //conversion.XMLCreators.convertFile(String,String,char);
			         
			          
			          
		        }
			     ;
			      
			    }
			}
		});
		frmFaiaPourFidexpert.getContentPane().setLayout(null);
		btnNewButton.setForeground(Color.BLACK);
		btnNewButton.setFont(new Font("Yu Gothic UI", Font.BOLD, 14));
		btnNewButton.setBackground(new Color(168, 146, 28));
		frmFaiaPourFidexpert.getContentPane().add(btnNewButton);
		
		JLabel lblNewLabel = new JLabel("");
		lblNewLabel.setBounds(0, 14, 456, 328);
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel.setIcon(new ImageIcon(fenetre.class.getResource("/image/fid.png")));
		frmFaiaPourFidexpert.getContentPane().add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("                Conversion fichier pour FAIA");
		lblNewLabel_1.setBounds(0, 0, 456, 24);
		lblNewLabel_1.setBackground(new Color(218, 165, 32));
		lblNewLabel_1.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 18));
		frmFaiaPourFidexpert.getContentPane().add(lblNewLabel_1);
		
		JMenuBar menuBar = new JMenuBar();
		frmFaiaPourFidexpert.setJMenuBar(menuBar);
		
		JMenu mnNewMenu = new JMenu("Aide");
		JMenuItem menuItem = new JMenuItem("?");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String w = e.getActionCommand();
				JFrame frame = new JFrame();
				if (w.equals("?")) {
					JDialog d = new JDialog(frame, "Aide");
					JLabel l = new JLabel("Le bouton convertit un fichier .csv en .xml directement sur votre PC");
					d.getContentPane().add(l);
					d.setIconImage(Toolkit.getDefaultToolkit().getImage(fenetre.class.getResource("/image/lux.png")));
					d.setSize(400,100);
					d.setVisible(true);
				}
			}
		});
		mnNewMenu.add(menuItem);
		menuBar.add(mnNewMenu);
	}

}

and the conversion class
Java
<pre>package image;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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 org.w3c.dom.Element;

public class conversion {
    public static void main(String[] args) {
        new conversion();
    }

   // public conversion() {
    //    new XMLCreators().convertFile("Test.csv", "Test.xml", '\t');
    //}

    public class XMLCreators {
        // Protected Properties

        protected DocumentBuilderFactory domFactory = null;
        protected DocumentBuilder domBuilder = null;

        public XMLCreators() {
            try {
                domFactory = DocumentBuilderFactory.newInstance();
                domBuilder = domFactory.newDocumentBuilder();
            } catch (FactoryConfigurationError exp) {
                System.err.println(exp.toString());
            } catch (ParserConfigurationException exp) {
                System.err.println(exp.toString());
            } catch (Exception exp) {
                System.err.println(exp.toString());
            }
        }

        public int convertFile(String csvFileName, String xmlFileName, char delimiter) {

            int rowsCount = -1;
            BufferedReader csvReader;
		System.out.println(csvFileName)
		System.out.println(csvReader)
            try {
                Document newDoc = domBuilder.newDocument();
                // Root element
                Element rootElement = newDoc.createElement("XMLCreators");
                newDoc.appendChild(rootElement);
                // Read csv file
                csvReader = new BufferedReader(new FileReader(csvFileName));
		System.out.println(csvFileName)

                //** Now using the OpenCSV **//
                CSVParser parser = new CSVParserBuilder()
                        .withSeparator(delimiter)
                        .build();

                CSVReader reader = new CSVReaderBuilder(new FileReader(csvFileName))
                        .withCSVParser(parser)
                        .build();
                //CSVReader reader = new CSVReader(csvReader);
                String[] nextLine;
                int line = 0;
                List<String> headers = new ArrayList<String>(5);
                while ((nextLine = reader.readNext()) != null) {
                    if (line == 0) { // Header row
                        for (String col : nextLine) {
                            headers.add(col);
                        }
                    } else { // Data row
                        Element rowElement = newDoc.createElement("row");
                        rootElement.appendChild(rowElement);

                        int col = 0;
                        for (String value : nextLine) {
                            String header = headers.get(col).replaceAll("[\\t\\p{Zs}\\u0020]", "_");

                            Element curElement = newDoc.createElement(header);
                            curElement.appendChild(newDoc.createTextNode(value.trim()));
                            rowElement.appendChild(curElement);

                            col++;
                        }
                    }
                    line++;
                }
                //** End of CSV parsing**//

                FileWriter writer = null;

                try {

                    writer = new FileWriter(new File(xmlFileName));

                    TransformerFactory tranFactory = TransformerFactory.newInstance();
                    Transformer aTransformer = tranFactory.newTransformer();
                    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                    aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

                    Source src = new DOMSource(newDoc);
                    Result result = new StreamResult(writer);
                    aTransformer.transform(src, result);

                    writer.flush();

                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (Exception e) {
                    }
                }

                // Output to console for testing
                // Resultt result = new StreamResult(System.out);
            } catch (IOException exp) {
                exp.printStackTrace();
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            return rowsCount;
            // "XLM Document has been created" + rowsCount;
        }
    }
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900