我一直在编写这段代码,将我的 XML 文件解析到 MySQL 数据库中。我在网上看到的每个教程都是单独解析的,就像我一直在研究的这段代码一样。从这里开始,我想以一种方式循环它,而不是单独添加每个字段,如果通过 XML 文件迭代它并定义需要在表内创建多少个字段。有谁知道他们有这样的教程,或者可能有一个简短的例子,我如何开始这样做?示例 我不想每次决定为客户添加另一个特征时都重新编辑我的程序。
package xSQLTEST;
import java.io.*;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class InsertXMLData {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/brandonDB",
"root",
"Absolute!");
Statement st = con.createStatement();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("C:\\testXML.xml"));
doc.getDocumentElement().normalize();
System.out.println("Root element of the doc is "
+ doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("row");
for (int s = 0; s < listOfPersons.getLength(); s++) {
Node firstPersonNode = listOfPersons.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
// -------------------------------------------------------------------------------------
NodeList CustIdList = firstPersonElement.getElementsByTagName("CustId");
Element CustIdElement = (Element) CustIdList.item(0);
NodeList textIDList = CustIdElement.getChildNodes();
String CustId = ((Node) textIDList.item(0)).getNodeValue()
.trim();
NodeList NameList = firstPersonElement.getElementsByTagName("Name");
Element NameElement = (Element) NameList.item(0);
NodeList textNMList = NameElement.getChildNodes();
String Name = ((Node) textNMList.item(0)).getNodeValue().trim();
NodeList CityList = firstPersonElement.getElementsByTagName("City");
Element CityElement = (Element) CityList.item(0);
NodeList textCTList = CityElement.getChildNodes();
String City = ((Node) textCTList.item(0)).getNodeValue().trim();
int i = st.executeUpdate("insert into customer(CustId,Name,City) values('"
+ CustId
+ "','"
+ Name
+ "','"
+ City
+ "')");
}
}
System.out.println("Data is successfully inserted!");
}
catch (Exception err) {
System.out.println(" " + err.getMessage());
}
}
}
我正在使用的 XML 文件,但希望将来添加有关客户的更多详细信息。
<Customers>
<row>
<CustId>1</CustId>
<Name>Woodworks</Name>
<City>Baltimore</City>
</row>
<row>
<CustId>2</CustId>
<Name>Software Solutions</Name>
<City>Boston</City>
</row>
<row>
<CustId>3</CustId>
<Name>Food Fantasies</Name>
<City>New York</City>
</row>
</Customers>
缓冲区读取器已插入并工作:
BufferedReader br = new BufferedReader(new FileReader(new File("c:\\testXML.xml")));
String line;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
String strFileContent = sb.toString();
最佳答案
使用 Jsoup,您可以执行以下操作:
private static void parseXml(String xml) {
Document doc = Jsoup.parse(xml);
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);
}
}
输出:
insert into customer(custid,name,city) values(1,Woodworks,Baltimore)
insert into customer(custid,name,city) values(2,Software Solutions,Boston)
insert into customer(custid,name,city) values(3,Food Fantasies,New York)
这允许我们添加任意数量的新列或行。例如,我在您的原始 XML 中添加了一些位,并且在不修改 java 代码的情况下,输出为:
insert into customer(custid,name,city,age) values(1,Woodworks,Baltimore,21)
insert into customer(custid,name,city,age) values(2,Software Solutions,Boston,21)
insert into customer(custid,name,city,age) values(3,Food Fantasies,New York,21)
insert into customer(custid,name,city,age) values(4,Crazy Hat Store,London,21)
编辑:
要从文件导入 XML,方法如下所示:
private static String loadXml(String filePath) {
try {
StringBuilder xml = new StringBuilder();
Scanner scanner = new Scanner(new File(filePath)); // i.e. C:\\testXML.xml
while (scanner.hasNextLine()) {
xml.append(scanner.nextLine());
}
return xml.toString();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
然后我的主要方法如下所示:
public static void main(String[] args) {
parseXml(loadXml(filePath));
}
关于java - XML 解析到 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24070399/