java - 如何在 Java 中读取 XML 响应 CSV 数据
问题描述
我有如下数据:
<?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 中读取此类数据?
解决方案
您需要解析 XML 并提取<response>标记的文本内容。该文本内容本质上是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,包括用于 XML 处理的 Java API (JAXP),它是 Oracle 的 Java 教程中的线索之一。
推荐阅读
- database - 更新单个模式的序列不起作用(Postgres 12)
- html - Django HTML在提交时将POST数据作为PK值发送到url
- python - 带循环的 Ansible 用户部署任务
- oracle - 在多个表上分组
- r - 从外部函数更改警告消息
- java - HTTP 服务器中的 Java 垃圾收集(Spring Boot/Spring Web)
- c# - 从 NuGet 包访问文件时出错
- intellij-idea - 如何在 IntelliJ 中调试项目并提供上下文 xml 文件?
- delphi - 有没有办法知道 IMAP4 服务器的已发送电子邮件的文件夹名称?
- python - 将 TensorFlow 列转换为类别索引