簡體   English   中英

使用for循環解析XML文件

[英]Parsing XML file using a for loop

我一直在研究將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接口。 而您真的想使用Jsoup中的Element

刪除行-導入org.w3c.dom。*

添加行import org.jsoup.Jsoup。 * ; (請注意*)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM