如何在 Java 中读取 XML 响应 CSV 数据

发布时间:2021-02-25 14:01

我有如下数据:

<?xml version="1.0"?>
<response>
"product_code","description","brand_Code","price","start_date","end_date","earliest_shipping_date","status","available_indicator"
"139005L","Cheryl's Crunchy Tree Cookies - Caseof 48","1001","74.9100","2013-12-03","2021-12-31","2013-12-05","A","Y"
"139057","Cheryl's Get Well Cookie Cards - Case of 25","1001","40.6300","2014-01-10","2021-12-31","2014-01-20","A","N"
</response>

我需要读取这些数据并作为行插入到表中。
如何在 Java 中读取此类数据?

回答1

您需要解析 XML 并提取 标记的文本内容。该文本内容本质上是 CSV 文件的内容。根据您问题中的示例 XML,我假设您想跳过第一行并将剩余的每一行拆分为单独的值。以下代码演示了如何执行此操作。请注意,我将您问题中的 XML 数据复制到了一个名为 response.xml 的文件中。

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlParse {
    public static void main(String[] args) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new File("response.xml"));
            NodeList responses = doc.getElementsByTagName("response");
            int count = responses.getLength();
            String verb = count == 1 ? "is" : "are";
            String plural = count == 1 ? "" : "s";
            System.out.printf("There %s %d response%s.%n", verb, count, plural);
            Node response = responses.item(0);
            String content = response.getTextContent();
            String[] lines = content.split("\n");
            count = lines.length;
            verb = count == 1 ? "is" : "are";
            plural = count == 1 ? "" : "s";
            System.out.printf("There %s %d line%s.%n", verb, count, plural);
            for (int i = 2; i < 4; i++) {
                String[] columns = lines[i].split(",");
                System.out.println(Arrays.toString(columns));
            }
        }
        catch (IOException | ParserConfigurationException | SAXException x) {
            x.printStackTrace();
        }
    }
}

这是我运行上述代码时得到的输出。

There is 1 response.
There are 4 lines.
["139005L", "Cheryl's Crunchy Tree Cookies - Caseof 48", "1001", "74.9100", "2013-12-03", "2021-12-31", "2013-12-05", "A", "Y"]
["139057", "Cheryl's Get Well Cookie Cards - Case of 25", "1001", "40.6300", "2014-01-10", "2021-12-31", "2014-01-20", "A", "N"]

请注意,我不想猜测您的意思...

<块引用>

按行插入表格

你是说数据库表吗?

有很多在线教程解释了如何使用 Java 代码解析 XML,包括 Java API for XML Processing (JAXP),这是 Oracle 的 Java 教程中的路径之一。