尝试写入XML文件时出错

时间:2014-10-28 12:26:12

标签: java xml csv

我正在尝试在线阅读CSV文件并将其转换为XML代码。我正在使用this答案的变体,但我仍然遇到同样的错误:

INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.

这是我的代码:

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import javax.swing.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;
import javax.naming.spi.DirStateFactory.Result;

import org.w3c.dom.Document;




public class XMLCreator {

    DocumentBuilderFactory domFactory = null;
    DocumentBuilder domBuilder = null;

    public static void main(String[] args) {
        XMLCreator xml = new XMLCreator();
        xml.convertFile("testThis", "");

      }

    public XMLCreator() {

        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 xmlFileName, String delimiter) {


        int rowsCount = -1;
        try {
            Document newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("XMLCreator");
            newDoc.appendChild(rootElement);
            // Read csv file
            BufferedReader csvReader;
            //csvReader = new BufferedReader(new FileReader("http://example.com/public/ex.csv"));
            URL csvUrl = new URL("http://example.com/public/ex.csv");
            URLConnection urlCon = (URLConnection) csvUrl.openConnection(); 
            InputStreamReader inStream = new InputStreamReader(urlCon.getInputStream());

            csvReader = new BufferedReader(inStream);

            int line = 0;
            List<String> headers = new ArrayList<String>(5);

            String text = null;
            while ((text = csvReader.readLine()) != null) {

                StringTokenizer st = new StringTokenizer(text, delimiter, false);
                String[] rowValues = new String[st.countTokens()];
                int index = 0;
                while (st.hasMoreTokens()) {

                    String next = st.nextToken();
                    rowValues[index++] = next;

                }

                if (line == 0) { // Header row

                    for (String col : rowValues) {
                        headers.add(col);
                    }

                } else { // Data row

                    rowsCount++;

                    Element rowElement = newDoc.createElement("row");
                    rootElement.appendChild(rowElement);
                    for (int col = 0; col < headers.size(); col++) {

                        String header = headers.get(col);
                        String value = null;

                        if (col < rowValues.length) {

                            value = rowValues[col];

                        } else {
                            // ?? Default value
                            value = "";
                        }
                        System.out.println(header+"="+value); 
                        Element curElement = newDoc.createElement(header);
                        curElement.appendChild(newDoc.createTextNode(value));
                        rowElement.appendChild(curElement);

                    }

                }
                line++;
                rowsCount = line;
            }

            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);
                StreamResult 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
            // Result result = new StreamResult(System.out);

        } catch (IOException exp) {
            System.err.println(exp.toString());
        } catch (Exception exp) {
            System.err.println(exp.toString());
        }
        System.out.print(rowsCount);
        return rowsCount;
        // "XLM Document has been created" + rowsCount;
    }
}

0 个答案:

没有答案