简体   繁体   English

使用 JAVA 将 CSV 文件转换为层次结构 XML

[英]Converting CSV file to Hierarchy XML with JAVA

We have a program in Java that needs to convert CSV file to Hierarchy XML:我们在 Java 中有一个程序,需要将 CSV 文件转换为层次结构 XML:

the output should be like this: output 应该是这样的:

`<?xml version="1.0" encoding="UTF-8"?>
<UteXmlComuniction xmlns="http://www....../data">
    <Client Genaral Data>
        <Client>
            <pfPg></pfPg>  
            <name>Arnold</name>
            <Family>Bordon</family>
        </Client>
        <Contract>
            <ContractDetail>
                <Contract>100020</Contract>
                <ContractYear>2019</ContractYear>
            </ContractDetail>
         </Contract>
    </Client Genaral Data>``

But for CSV file we are flexible, we can define it as we want.但是对于 CSV 文件我们是灵活的,我们可以根据需要定义它。 I thought maybe in this way it works:我想也许它是这样工作的:

"UteXmlComuniction/ClientGeneralData/Client/pfpg", "UteXmlComuniction/ClientGeneralData/Client/name" , 
"UteXmlComuniction/ClientGeneralData/Client/Family" , ...```

This is our code, but it just gives me the flat XML.这是我们的代码,但它只是给了我平坦的 XML。 Also I can not insert "/" character in CSV file, because program can not accept this character.我也不能在 CSV 文件中插入"/"字符,因为程序不能接受这个字符。

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

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

            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 = "";
                        }

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

                    }

                }
                line++;

            }

            ByteArrayOutputStream baos = null;
            OutputStreamWriter osw = null;

            try {

                baos = new ByteArrayOutputStream();
                osw = new OutputStreamWriter(baos);

                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(osw);
                aTransformer.transform(src, result);

                osw.flush();
                System.out.println(new String(baos.toByteArray()));

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

            // Output to console for testing
            // Resultt result = new StreamResult(System.out);

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

Do you have any suggestion that how should I modify the code or how can I change my CSV in order to have a Hierarchy XML?你有什么建议我应该如何修改代码或如何更改我的 CSV 以获得层次结构 XML?

csv: pfPg;name;Family;Contract;ContractYear csv:pfPg;姓名;家庭;合同;合同年

There are several libs for reading csv in Java. Java 中有几个库用于读取 csv。 Store the values in a container eg hashmap.将值存储在容器中,例如 hashmap。

Then create java classes representing your xml structure.然后创建代表您的 xml 结构的 java 类。

class Client {
private String pfPg;
private String name;
private String Family
}

class ClientGenaralData {
private Client client;
private Contract contract;
}

Do the mapping from csv to your Java classes by writing custom code or a mapper like dozer... Then use xml binding with Jackson or JAXB to create xml from Java objects. Do the mapping from csv to your Java classes by writing custom code or a mapper like dozer... Then use xml binding with Jackson or JAXB to create xml from Java objects.

Jackson xml Dozer HowTo Jackson xml推土机操作指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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