java - 使用 JAVA 将 CSV 文件转换为 Hierarchy XML

标签 java xml csv

我们有一个 Java 程序,需要将 CSV 文件转换为 Hierarchy XML:

输出应该是这样的:

`<?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>``

但是对于 CSV 文件我们很灵活,我们可以根据需要定义它。我想也许可以这样工作:

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

这是我们的代码,但它只提供了平面 XML。另外,我无法在 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;
    }
}

您对我应该如何修改代码或如何更改我的 CSV 以获得层次结构 XML 有什么建议吗?

最佳答案

csv: pfPg;姓名;家庭;契约(Contract);契约(Contract)年份

有几个用于在 Java 中读取 csv 的库。将值存储在容器中,例如 HashMap 。

然后创建代表您的 xml 结构的 java 类。

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

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

通过编写自定义代码或像推土机这样的映射器来完成从 csv 到 Java 类的映射...然后使用 xml 与 Jackson 或 JAXB 绑定(bind)从 Java 对象创建 xml。

Jackson xml Dozer HowTo

关于java - 使用 JAVA 将 CSV 文件转换为 Hierarchy XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61370034/

相关文章:

java - 网络代码有时会抛出 UnknownHostException

iphone - 使用 NSXMLParser 解析时,它是下载整个 .xml 然后解析,还是进行流式解析?

ios - 从 iOS 应用程序调用网络服务

python - 获取 CSV 文件中特定范围的数据 (Python)

java - 无法在 if 语句中向变量添加数字

java - 如果我将加密的 html 文件解析为字符串,我可以以某种方式从中获取文本吗?

java - 在 Java 中调用模糊重载的构造函数

html - XML 中 "Unit Separator"的最佳值是多少?

string - 为什么golang bytes.Buffer会以这种方式运行?

python - 将制表符分隔的 .txt 解析为 Pandas DataFrame