gpt4 book ai didi

java - 使用 for 循环解析 XML 文件

转载 作者:行者123 更新时间:2023-11-29 12:55:40 26 4
gpt4 key购买 nike

我一直在开发这个程序,它将 XML 文件插入 MYSQL 数据库。我对插入包的整个 .jar 想法很陌生。我遇到了 parse()、select() 和 Children() 的问题。有人可以告诉我如何解决这个问题吗?这是我的堆栈跟踪和下面的程序:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The method select(String) is undefined for the type Document
The method children() is undefined for the type Element
The method children() is undefined for the type Element
The method children() is undefined for the type Element
The method children() is undefined for the type Element

at jdbc.parseXML.main(parseXML.java:28)
<小时/>
import java.io.*;
import java.sql.*;

import org.jsoup.Jsoup;
import org.w3c.dom.*;

import javax.xml.parsers.*;

public class parseXML{
public static void main(String xml) {

try{
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\staff.xml")));
String line;
StringBuilder sb = new StringBuilder();

while((line=br.readLine())!= null){
sb.append(line.trim());
}

Document doc = Jsoup.parse(line);

StringBuilder queryBuilder;
StringBuilder columnNames;
StringBuilder values;

for (Element row : doc.select("row")) {
// Start the query
queryBuilder = new StringBuilder("insert into customer(");
columnNames = new StringBuilder();
values = new StringBuilder();

for (int x = 0; x < row.children().size(); x++) {

// Append the column name and it's value
columnNames.append(row.children().get(x).tagName());
values.append(row.children().get(x).text());

if (x != row.children().size() - 1) {
// If this is not the last item, append a comma
columnNames.append(",");
values.append(",");
}
else {
// Otherwise, add the closing paranthesis
columnNames.append(")");
values.append(")");
}
}

// Add the column names and values to the query
queryBuilder.append(columnNames);
queryBuilder.append(" values(");
queryBuilder.append(values);

// Print the query
System.out.println(queryBuilder);
}

}catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
}
}

最佳答案

两个独立的库名称冲突 - 因此当您使用 Element 时,编译器会查看 org.w3c.dom.* 中的 Element 接口(interface);而你确实想使用 Jsoup 中的 Element

删除该行 - 导入 org.w3c.dom.*

添加行 导入 org.jsoup.Jsoup.*; (注意*)

关于java - 使用 for 循环解析 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com